php laravel model,Laravel创建Model命令

由于数据库表太多不想一个个创建基础的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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值