Laravel:更改数据库中的时间戳名称

Jac*_*chi 1 laravel sql-timestamp

我正在尝试重命名数据库中表的时间戳列(created_atupdated_at) 。user我已经看到了这个答案,但是当我重写CREATED_ATUPDATED_AD常量时:

class User extends Authenticatable
{
    const CREATED_AT = 'user_creation_date';
    const UPDATED_AT = 'user_update_date';
    ...
}
Run Code Online (Sandbox Code Playgroud)

它所做的只是重命名模型的属性User,即$user->user_creation_date$user->user_update_date。数据库列保持不变。我应该如何重命名数据库的列,同时保留自动更新功能?

感谢您的帮助。

ali*_*col 5

您将需要更新您的用户表迁移文件database/migrations,它将是一个类似于2014_10_12_000000_create_users_table.php.

您可能正在通话$table->timestamps();Schema::create

查看timestamp()其中的代码可以vendor/laravel/framework/src/Illuminate/Database/Schema/Blueprint.php发现:

public function timestamps($precision = 0)
{
    $this->timestamp('created_at', $precision)->nullable();

    $this->timestamp('updated_at', $precision)->nullable();
}
Run Code Online (Sandbox Code Playgroud)

所以:

Schema::create('users', function (Blueprint $table) {
  // ..
  $table->timestamps();
});
Run Code Online (Sandbox Code Playgroud)

删除调用$table->timestamps();并添加添加要调用时间戳的两列:

Schema::create('users', function (Blueprint $table) {
  // ..
  $this->timestamp('user_creation_date', 0)->nullable();
  $this->timestamp('user_update_date', 0)->nullable();
});
Run Code Online (Sandbox Code Playgroud)

您将需要再次运行迁移,确保备份数据,因为这将删除表并重新创建它们。

希望这可以帮助。