在laravel迁移中设置默认的空数组



我想为列兴趣设置空数组。我已经将字段添加为json,并在模型中将其强制转换为数组。以下是我的代码片段:

/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('db_invitations', function (Blueprint $table) {
if(!Schema::hasColumn('db_invitations','interests')){
$table->json('interests');
}
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('db_invitations', function (Blueprint $table) {
if(Schema::hasColumn('db_invitations','interests')){
$table->dropColumn('interests');
}
});
}

也在型号中:

/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'interests' => 'array'
];

那么,我需要做些什么才能在兴趣栏中显示default[]呢?

在MySQL中,json数据类型不能有默认值。请改用$attributes

/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'interests' => 'array',
];
protected $attributes = [
'interests' => [],
];

只要有人来过它,您就可以对json和字符串执行此操作:

$table->字符串("字段")->默认值(json_encode([]));

相关内容

  • 没有找到相关文章

最新更新