You need to enable JavaScript to run this app. 在Laravel迁移中为已有text列设置默认值不生效如何解决
优惠活动
大模型
产品
解决方案
定价
更多

在Laravel迁移中为已有text列设置默认值不生效如何解决

问题解决方法
  • 第一步:安装字段修改依赖
    Laravel 修改已有字段属性需要依赖 doctrine/dbal 包,先执行命令安装:
composer require doctrine/dbal
  • 第二步:修正迁移代码
    你当前的修改迁移没有保留原字段的nullable属性,会导致结构变更不符合预期,修改ChangeEmailValidationUserDefaultValue迁移的up方法代码:
Schema::table('experience_settings', function (Blueprint $table) {
    $table->text('email_validation_user')
        ->default('Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised')
        ->nullable() // 保留原字段允许为空的属性
        ->change();
});

同时补充down方法的回滚逻辑:

public function down()
{
    Schema::table('experience_settings', function (Blueprint $table) {
        $table->text('email_validation_user')->nullable()->default(null)->change();
    });
}
  • 第三步:兼容低版本MySQL方案
    如果你的MySQL版本低于8.0,数据库层面不支持TEXT类型设置默认值,直接通过模型层设置默认值即可,效果和数据库默认值完全一致:
    打开对应的ExperienceSetting模型,添加默认属性配置:
protected $attributes = [
    'email_validation_user' => 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industrys standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised'
];
  • 第四步:验证插入逻辑
    检查你插入数据的代码,不要显式给email_validation_user字段传入null或者空字符串,否则会覆盖默认值配置。

内容的提问来源于stack exchange,提问作者testCode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 06:06:03