1

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

class User extends Authenticatable
{
    const CREATED_AT = 'user_creation_date';
    const UPDATED_AT = 'user_update_date';
    ...
}

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

谢谢您的帮助。

4

2 回答 2

4

您将需要更新您的 users 表迁移文件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();
}

所以:

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

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

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

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

希望这可以帮助。

于 2018-05-09T08:38:10.197 回答
1

您可以使用获取属性,例如

class User extends Authenticatable
{
    protected $timestamps = true;
    protected $hidden = ['created_at', 'updated_at']; 
    protected $appends = ['user_creation_date', 'user_update_date']; 
    public function getUserCreationDateAttribute(){
        return $this->created_at; 
    }
    public function getUserUpdateDateAttribute(){
        return $this->updated_at; 
    }
}

现在您将获得字段和中的列created_atupdated_at数据。当您返回或响应或转换为or时,这些字段将保持隐藏状态。user_creation_dateuser_update_datecreated_atupdated_atarrayjsonobjectarrayjson

于 2018-05-09T08:35:51.753 回答