快速获取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 协议》,转载必须注明作者和本文链接
每天一点小知识,到那都是大佬,哈哈
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 3

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

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

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