首页 > 开发 > PHP > 正文

分享8个Laravel模型时间戳使用技巧小结

2024-05-04 22:53:18
字体:
来源:转载
供稿:网友

 默认情况下,Laravel Eloquent 模型默认数据表有 created_at 和 updated_at 两个字段。当然,我们可以做很多自定义配置,实现很多有趣的功能。下面举例说明。

1. 禁用时间戳

如果数据表没有这两个字段,保存数据时 Model::create($arrayOfValues); —— 会看到 SQL error。Laravel 在自动填充 created_at / updated_at 的时候,无法找到这两个字段。

禁用自动填充时间戳,只需要在 Eloquent Model 添加上一个属性:

class Role extends Model{  public $timestamps = FALSE;  // ... 其他的属性和方法}

2. 修改时间戳默认列表

假如当前使用的是非 Laravel 类型的数据库,也就是你的时间戳列的命名方式与此不同该怎么办? 也许,它们分别叫做 create_time 和 update_time。恭喜,你也可以在模型种这么定义:

class Role extends Model{  const CREATED_AT = 'create_time';  const UPDATED_AT = 'update_time'; 

3. 修改时间戳日期 / 时间格式

以下内容引用官网文档 official Laravel documentation:

默认情况下,时间戳自动格式为 'Y-m-d H:i:s'。 如果您需要自定义时间戳格式,可以在你的模型中设置 $dateFormat 属性。这个属性确定日期在数据库中的存储格式,以及在序列化成数组或 JSON 时的格式:

class Flight extends Model{  /**   * 日期时间的存储格式   *   * @var string   */  protected $dateFormat = 'U';}

4. 多对多:带时间戳的中间表

当在多对多的关联中,时间戳不会自动填充,例如 用户表  users 和 角色表 roles 的中间表 role_user。

在这个模型中您可以这样定义关系:

class User extends Model{  public function roles()  {    return $this->belongsToMany(Role::class);  }}

然后当你想用户中添加角色时,可以这样使用:

$roleID = 1;$user->roles()->attach($roleID);

默认情况下,这个中间表不包含时间戳。并且 Laravel 不会尝试自动填充 created_at/updated_at

但是如果你想自动保存时间戳,您需要在迁移文件中添加 created_at/updated_at,然后在模型的关联中加上 ->withTimestamps();

public function roles(){  return $this->belongsToMany(Role::class)->withTimestamps();}

5. 使用 latest() 和 oldest() 进行时间戳排序

使用时间戳排序有两个 “快捷方法”。

取而代之:

User::orderBy('created_at', 'desc')->get();

这么做更快捷:

User::latest()->get();

默认情况,latest() 使用 created_at 排序。

与之对应,有一个 oldest() ,将会这么排序 created_at ascending

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表