Laravel修改默认时间戳列名失败,如何改为brandCreatedAt和brandUpdatedAt?
解决Laravel自定义时间戳列名的问题
问题出在迁移文件的写法:你模型里定义的CREATED_AT和UPDATED_AT常量是给Laravel ORM用的,用来识别自定义时间戳列,但迁移文件里的$table->timestamps()方法会固定生成created_at和updated_at列,和模型设置无关。
正确的解决步骤:
修改迁移文件
把默认的$table->timestamps()替换为自定义的时间戳列定义,示例如下:public function up() { Schema::create('brands', function (Blueprint $table) { $table->id(); $table->string('brandName')->nullable(); $table->string('brandIsActive')->nullable(); // 替换timestamps()为自定义列 $table->timestamp('brandCreatedAt')->useCurrent(); $table->timestamp('brandUpdatedAt')->useCurrent()->useCurrentOnUpdate(); }); }如果需要允许空值,可以给列加上
->nullable()。处理已执行的迁移
- 如果还没有生产数据,直接回滚迁移再重新执行:
php artisan migrate:rollback php artisan migrate - 如果已有数据,需要创建新的迁移来修改表结构:
然后在新迁移的php artisan make:migration alter_brands_add_custom_timestampsup方法中添加:
执行迁移:public function up() { Schema::table('brands', function (Blueprint $table) { // 先删除默认的时间戳列 $table->dropTimestamps(); // 添加自定义列 $table->timestamp('brandCreatedAt')->useCurrent()->nullable(); $table->timestamp('brandUpdatedAt')->useCurrent()->useCurrentOnUpdate()->nullable(); }); }php artisan migrate
- 如果还没有生产数据,直接回滚迁移再重新执行:
确认模型设置
确保你的Brand模型中已经正确定义常量:class Brand extends Model { use HasFactory; const CREATED_AT = 'brandCreatedAt'; const UPDATED_AT = 'brandUpdatedAt'; protected $table = 'brands'; // 若模型名与表名符合Laravel复数规范,可省略该定义 }清除缓存(可选但推荐)
执行以下命令确保配置和模型缓存被清除:php artisan cache:clear php artisan config:clear php artisan optimize:clear
这样修改后,Laravel ORM会自动使用你定义的brandCreatedAt和brandUpdatedAt列处理时间戳,迁移也会生成正确的列名。
内容的提问来源于stack exchange,提问作者Pasindu Ruwandeniya
相关产品推荐
相关产品推荐

