在 Laravel 迁移中设置默认空数组

问题描述 投票:0回答:2

我想为列兴趣设置空数组。我已将字段添加为 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'
    ];

那么我需要做什么才能在兴趣栏中显示默认[]?

mysql laravel migration
2个回答
6
投票

MySQL 中的 json 数据类型不能有默认值。请使用

$attributes
来代替。

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

protected $attributes = [
    'interests' => [],
];

0
投票

如果有人遇到它,你可以对 json 和 string 执行此操作:

$table->string('field')->default(json_encode([]));

© www.soinside.com 2019 - 2024. All rights reserved.