如何使用Laravel迁移新增默认值与created_at一致的updated_at字段
Laravel 迁移实现新增updated_at字段同步created_at初始值方案
问题原由
你当前的写法未指定默认值,表中存在历史数据时会因非空字段无填充值报错,也无法实现初始值与created_at同步的需求。
实现代码
Laravel 9+ 版本
use Illuminate\Support\Facades\DB; Schema::table($this->tableName(), function (Blueprint $table) { $table->timestamp('updated_at') ->default(DB::raw('`created_at`')) ->useCurrentOnUpdate(); });
Laravel 8及更低版本
use Illuminate\Support\Facades\DB; Schema::table($this->tableName(), function (Blueprint $table) { $table->timestamp('updated_at') ->default(DB::raw('`created_at`')) ->onUpdate(DB::raw('CURRENT_TIMESTAMP')); });
代码说明
default(DB::raw('created_at')):新增字段时自动将所有历史行的updated_at值同步为对应行的created_at,解决已有数据的填充问题useCurrentOnUpdate()/onUpdate(DB::raw('CURRENT_TIMESTAMP')):后续行数据更新时自动刷新updated_at为当前时间,符合Laravel时间戳字段的常规维护逻辑- 若你的模型已开启
public $timestamps = true(Laravel默认开启),新增字段后无需额外修改模型代码,框架会自动维护两个时间戳字段
回滚迁移代码
在迁移文件的down方法中添加以下逻辑用于回滚操作:
Schema::table($this->tableName(), function (Blueprint $table) { $table->dropColumn('updated_at'); });
内容的提问来源于stack exchange,提问作者JanKobylak
相关产品推荐
相关产品推荐

