在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
相关产品推荐
相关产品推荐

