【问题标题】:Set default empty array in laravel migration在 laravel 迁移中设置默认的空数组
【发布时间】:2021-11-26 13:12:23
【问题描述】:

我想为列兴趣设置空数组。我已将字段添加为 json 并将其转换为我的模型中的数组。以下是我的代码 sn-ps :

/**
     * 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('[]') 也许?我的问题是,你为什么要这样做而不是保持 NULL 值?

标签: mysql laravel migration


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-23
    • 2016-09-05
    • 2015-02-17
    • 2016-10-06
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    相关资源
    最近更新 更多