快速获取Mysql 字段生成ORM的$fillable 属性,顺序和数据库保持一致

使用方式:

快速获取Mysql 字段生成fillable 属性

代码如下

<?php

namespace App\Console\Commands;

use DB;
use Illuminate\Console\Command;
use Illuminate\Database\Schema\Blueprint;

class GetTableColumns extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'tools:get-table-columns
                            {table : The table name}
                            {con? : The table connection}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获取数据库字段';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $table = $this->argument('table');

        $connection = $this->argument('con');

        $con = $connection ?: 'mysql';

        $db = config('database.connections.'.$con.'.database');

        $columns = DB::select('select column_name from information_schema.columns where table_name= ? and TABLE_SCHEMA = ? order by `ordinal_position`', [$table, $db]);

        $columns = array_column($columns, 'COLUMN_NAME');

        $columns = array_diff($columns, ['id', 'created_at', 'updated_at', 'deleted_at']);

        $this->newLine();

        $this->info('protected $fillable = [');

        foreach ($columns as $column) {
            $this->info("    '".$column."',");
        }

        $this->info('];');

        return 0;
    }
}

下面这种方式也能获取字段,但是有个问题是顺序会打乱(不推荐):
$columns = DB::connection()->getSchemaBuilder()->getColumnListing($table);

本作品采用《CC 协议》,转载必须注明作者和本文链接
每天一点小知识,到那都是大佬,哈哈
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 3

laravel 有轮子的 Schema::connection('connection')->getColumnListing("table_name")

9个月前 评论
raybon (楼主) 9个月前
raybon (楼主) 9个月前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!