自定义了一个批量生成model文件的命令

zhezhebie

生成内容如下:

<?php

namespace app\model;

use support\Model;

class MsDspNotice extends Model
{
    protected $table = 'ms_notice';
    // 其他模型配置...

    protected $primaryKey = 'id';
    protected $fillable = [
        'title',
        'notice',
        'addtime',
        'status',
    ];
}

源代码如下:希望大家可以继续完善。

<?php

namespace app\command;

use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Support\Str;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class GenerateModel extends Command
{
    protected static $defaultName = 'generate:model';
    protected static $defaultDescription = 'generate model';

    /**
     * @return void
     */
    protected function configure()
    {
        $this->addArgument('name', InputArgument::OPTIONAL, 'Name description');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // 初始化 Illuminate Database Capsule
        $capsule = new Capsule;
        $capsule->addConnection(config('database.connections.mysql'));
        $capsule->setAsGlobal();
        $capsule->bootEloquent();

        // 获取所有表名
        $tables = $capsule->getConnection()->getSchemaBuilder()->getAllTables();
        // 生成 Model 文件
        foreach ($tables as $table) {
            $table = $table->Tables_in_duanshipin;
            $modelName = Str::studly($table);
            $filePath = app_path() . DIRECTORY_SEPARATOR . 'model' . DIRECTORY_SEPARATOR . $modelName . '.php';
            // 检查文件是否存在
            if (!is_file($filePath)) {
                // 如果不存在,则生成 Model 文件
                $this->generateModelFile($capsule, $table, $modelName, $filePath);
                $output->writeln("Model file generated: $modelName");
            } else {
                $output->writeln("Model file already exists: $modelName");
            }
        }

        $output->writeln('All model files generated successfully.');
        return 0;
    }

    protected function generateModelFile($capsule, $table, $modelName, $filePath)
    {

        $columns = $capsule->getConnection()->select("DESCRIBE $table;");
        foreach ($columns as $colmn) {
            $column_fields[] = $colmn->Field;
        }

        $column_fields = array_diff($column_fields, ['id']);
        $columns = '[' . PHP_EOL . '\'' . implode('\',' . PHP_EOL . ' \'', $column_fields) . '\'' . PHP_EOL . ']';

        $content = <<<EOF
<?php

namespace app\model;

use support\Model;

class $modelName extends Model
{
    protected \$table = '$table';
    // 其他模型配置...

    protected \$primaryKey = 'id';
    protected \$fillable = $columns;
}

EOF;

        file_put_contents($filePath, $content);
    }

}
226 0 0
0个评论

zhezhebie

180
积分
0
获赞数
0
粉丝数
2023-03-30 加入
🔝