Laravel通过artisan+模板自动生成Model

1、首先创建一个model模板

在resources下新增stubs文件夹,新建Model.stub文件,既你自己的模板文件

<?php

namespace App\Models;


class {{modelName}} extends Base
{

    protected $table = '{{tableName}}';

    public function getList()
    {

    }

    public function action($id,{{actionArgs}})
    {
        if($id == 0){
            return $this->create([
            {{createContent}}
            ]);
        }else{
            $this->where('id', $id)->update([
            {{updateContent}}
            ]);
            return $this->getInfo($id);
        }
    }
}

其他一些公共方法我已经提出来到Base.php中了

<?php

namespace App\Models;

use DateTimeInterface;
use Illuminate\Database\Eloquent\Model;

class Base extends Model
{
    public $timestamps = true;

   
    protected $dateFormat = 'U';

    protected $guarded = [];

    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
    ];


    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public function getInfo($id)
    {
        return $this->find($id);
    }

    public function changeField($id, $field, $data)
    {
        $this->where('id', $id)->update([$field => $data]);
    }


    public function getInfoByField($field, $data)
    {
        return $this->where($field, $data)->where('is_del', 0)->first();
    }
}

2、接下来创建artisan命令

php artisan make:command MakeModelCommand

执行以上命令,会在app/console/Commands中生成MakeModelCommand.php

接下来在MakeModelCommand中写生成代码

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class MakeModelCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:makeModelCommand {tables}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     */
    public function handle()
    {
        $tables = $this->argument('tables');
        $stub = file_get_contents(resource_path("stubs/Model.stub"));
        foreach (explode(',', $tables) as $table) {
            //获取字段
            $columns = Schema::getColumnListing($table);
            $modelName = $this->camelize($table);
            $actionArgs = $createContent = $updateContent = '';
            foreach ($columns as $columnKey => $column) {
                //以下字段我这里是自动维护的,所以不需要添加进方法中
                if (!in_array($column, ['id', 'updated_at', 'created_at', 'is_del'])) {
                    $argStr = $this->camelize($column, false);
                    $actionArgs .= " \${$argStr},";
                    if ($columnKey != 1) {
                        $createContent .= "\t\t\t\t";
                        $updateContent .= "\t\t\t\t";
                    } else {
                        $createContent .= "\t";
                        $updateContent .= "\t";
                    }
                    $createContent .= "'{$column}' => \${$argStr},\n";
                    $updateContent .= "'{$column}' => \${$argStr},\n";
                }
            }
            $actionArgs = rtrim($actionArgs, ',');
            $createContent = rtrim($createContent, ",\n");
            $updateContent = rtrim($updateContent, ",\n");
            $modelTemplate = str_replace(
                [
                    '{{modelName}}',
                    '{{tableName}}',
                    '{{actionArgs}}',
                    '{{createContent}}',
                    '{{updateContent}}',
                ],
                [
                    $modelName,
                    $table,
                    $actionArgs,
                    $createContent,
                    $updateContent
                ],
                $stub
            );
            file_put_contents(app_path("Models/{$modelName}.php"), $modelTemplate);
        }
    }

    /***
     * 下划线转驼峰
     * @param string $str  字符串
     * @param bool $firstToUpper 首字母是否大写
     * @return mixed|string
     */
    function camelize($str, $firstToUpper = true)
    {
        while (($pos = strpos($str, '_')) !== false)
            $str = substr($str, 0, $pos) . ucfirst(substr($str, $pos + 1));
        if ($firstToUpper)
            return ucfirst($str);
        else
            return $str;
    }
}

3、最后在命令行中执行代码即可

 php artisan command:makeModelCommand 表1,表2....

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值