快速获取Mysql 字段生成ORM的$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 协议》,转载必须注明作者和本文链接
laravel 有轮子的 Schema::connection('connection')->getColumnListing("table_name")