You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel修改默认时间戳列名失败,如何改为brandCreatedAt和brandUpdatedAt?

解决Laravel自定义时间戳列名的问题

问题出在迁移文件的写法:你模型里定义的CREATED_AT和UPDATED_AT常量是给Laravel ORM用的,用来识别自定义时间戳列,但迁移文件里的$table->timestamps()方法会固定生成created_at和updated_at列,和模型设置无关。

正确的解决步骤:

  1. 修改迁移文件
    把默认的$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()。

  2. 处理已执行的迁移

    • 如果还没有生产数据,直接回滚迁移再重新执行:
      php artisan migrate:rollback
      php artisan migrate
      
    • 如果已有数据,需要创建新的迁移来修改表结构:
      php artisan make:migration alter_brands_add_custom_timestamps
      
      然后在新迁移的up方法中添加:
      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
  3. 确认模型设置
    确保你的Brand模型中已经正确定义常量:

    class Brand extends Model
    {
        use HasFactory;
    
        const CREATED_AT = 'brandCreatedAt';
        const UPDATED_AT = 'brandUpdatedAt';
    
        protected $table = 'brands'; // 若模型名与表名符合Laravel复数规范,可省略该定义
    }
    
  4. 清除缓存(可选但推荐)
    执行以下命令确保配置和模型缓存被清除:

    php artisan cache:clear
    php artisan config:clear
    php artisan optimize:clear
    

这样修改后,Laravel ORM会自动使用你定义的brandCreatedAt和brandUpdatedAt列处理时间戳,迁移也会生成正确的列名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:35:15