php laravel model,Laravel创建Model命令

陆博易
2023-12-01

由于数据库表太多不想一个个创建基础的Model模板,所以就写了这个东东!

好了直接上代码把!

namespace App\Console\Commands;

use Illuminate\Console\Command;

use Illuminate\Support\Facades\DB;

class CreateModelCommand extends Command

{

/**

* The name and signature of the console command.

*

* @var string

*/

protected $signature = 'create:model {table_name}';

/**

* The console command description.

*

* @var string

*/

protected $description = '创建Model';

/**

* Create a new command instance.

*

* @return void

*/

public function __construct()

{

parent::__construct();

}

/**

* Execute the console command.

*

* @return mixed

*/

public function handle()

{

$table = $this->argument('table_name');

if('' === $table){

echo '参数错误';

return;

}

if('all' === $table){

// 所有表名称

$tables = DB::select('show tables;');

foreach ($tables as $table){

$this->createModel($table->Tables_in_community);

}

} else if($table){

$this->createModel($table);

}

echo '大功告成';

}

private function createModel(string $table): void

{

// c_为表前缀 改成自己的

$tableName = str_replace('c_','',$table);

$tableName = explode('_', $tableName);

$modelName = array_map(function ($value) {

return ucfirst($value);

}, $tableName);

$modelName = implode('', $modelName).'Model';

// Model存放目录可以自行修改

$fileName = app_path('/Models/').$modelName.'.php';

if(is_file($fileName)){

return;

}

$tableInfo = DB::select('show columns from ' . $table);

$pk = 'id';

foreach ($tableInfo as $fieldInfo) {

if ('PRI' === $fieldInfo->Key) {

$pk = $fieldInfo->Field;

break;

}

}

!is_file($fileName) && file_put_contents($fileName, $this->formatModelString($modelName, $pk, $table));

}

private function formatModelString(string $modelName, string $pk, string $table): string

{

$content = '<?php

namespace App\Models;

use App\Models\BaseModel;

class {{__MODEL_NAME__}} extends BaseModel

{

/**

* 重定义主键

*

* @var string

*/

protected $primaryKey = \'{{__PK__}}\';

/**

* 与模型关联的表名

*

* @var string

*/

protected $table = \'{{__TABLE_NAME__}}\';

/**

* 指示是否自动维护时间戳

*

* @var bool

*/

public $timestamps = false;

}';

return str_replace(['{{__MODEL_NAME__}}','{{__PK__}}', '{{__TABLE_NAME__}}'],

[$modelName, $pk, $table], $content);

}

}

 类似资料: