我正在构建一个自定义artisan命令,需要能够访问某些列的数据库的默认值。我不能使用属性数组。所以我需要另一种方式。
我试过用Schema
。我已经能够获得表DB::table($table)
和列名Schema::getColumnListings($table)
但不是默认值。
是否有其他方法来获取默认值?
Laravel Schema Builder仅按设计返回列名。但是你可以通过执行数据库语句使用Laravel在内部使用的相同方法:
$results = DB::select('
select column_default
from information_schema.columns
where
table_schema = ?
and table_name = ?
', [$database, $table]);
// Flatten the results to get an array of the default values
$defaults = collect($results)->pluck('column_default'))
上面的示例适用于MySQL数据库,但您可以通过搜索方法Illuminate\Database\Schema\Grammars
来查看Laravel源代码的compileColumnListing
命名空间中其他数据库的方法。