【问题标题】:Laravel: Change the timestamps' names in the databaseLaravel:更改数据库中时间戳的名称
【发布时间】:2018-10-19 07:14:38
【问题描述】:

我正在尝试重命名数据库中user 表的时间戳列(created_atupdated_at)。我已经看到了this answer,但是当我像这样覆盖CREATED_ATUPDATED_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。数据库列保持不变。如何在保留自动更新功能的同时重命名数据库的列?

感谢您的帮助。

【问题讨论】:

  • 实用问题:你为什么要这个?您的user 上的created_at 标记非常明显,表明当时创建了用户记录。在所有表中保持这些列名一致也便于以后查询。
  • 这只是在 SQL 查询中进行连接时更方便,而不是 table1.updated_at = table2.updated_at 你只需 table1_update_date = table2_update_date
  • 这实际上是 1 个字符的差异,对吧?无论如何,alistaircol 的答案可能是最好的答案。
  • 是的,我会测试它。正如你所说,这不是字符差异的问题,而是框架处理的问题。 ->where('table1_column','table2_column')DB::raw('table1.column = table2.column') 更容易。我不会选择老板让我做什么。
  • DB::table('table1')->join('table2', 'table1.created_at', '=', 'table2_created_at')->select('*')->get()? (或左连接:DB::table('table1')->leftJoin('table2', 'table1.created_at', '=', 'table2_created_at')->get())不要试图妨碍您,您可能有充分的理由!我只是很难看出解决你的问题到底有什么好处;)

标签: laravel sql-timestamp


【解决方案1】:

你可以使用get属性,例如

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; 
    }
}

现在您将在字段user_creation_dateuser_update_date 中获得created_atupdated_at 两列数据。当您返回 arrayjson 响应或将 object 转换为 arrayjson 时,字段 created_atupdated_at 将保持隐藏状态。

【讨论】:

  • 但是如果我想检索我的 JSON 中的时间戳怎么办 ;(
  • 您可以将其从 $hidden 中删除,它将返回所有四列。
  • JSON 属性是什么? updated_atuser_update_date?
  • 您将同时获得updated_atuser_update_date 以及created_atuser_creation_date$hidden 中设置的字段在 JSON 中不可见。
【解决方案2】:

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

Schema::create 呼叫中可能有 $table->timestamps();

查看vendor/laravel/framework/src/Illuminate/Database/Schema/Blueprint.phptimestamp() 的代码会发现:

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();
});

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

希望这会有所帮助。

【讨论】:

  • 是否保留更新栏的自动更新功能?
  • 我猜如果你在你的问题中定义了你的模型中的常量。
  • 我会测试它,我稍后告诉你。
猜你喜欢
  • 1970-01-01
  • 2016-05-29
  • 1970-01-01
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-11
相关资源
最近更新 更多