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

默认情况下,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;
u s e r > r o l e s ( ) > a t t a c h ( 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
User::oldest()->get();
复制代码当然,也可以使用指定的其他字段排序。例如,如果想要使用 updated_at,可以这么做:
$lastUpdatedUser = User::latest(‘updated_at’)->first();
复制代码
6. 不触发 updated_at的修改
无论何时,当修改 Eloquent 记录,都将会自动使用当前时间戳来维护 updated_at 字段,这是个非常棒的特性。
但是有时候你却不想这么做,例如:当增加某个值,认为这不是 “整行更新”。
那么,你可以一切如上—— 只需禁用 timestamps,记住这是临时的:
$user = User::find(1);
$user->profile_views_count = 123;
$user->timestamps = false;
$user->save();
复制代码
7. 仅更新时间戳和关联时间戳
与上一个例子恰好相反,也许您需要仅更新updated_at字段,而不改变其他列。
所以,不建议下面这种写法:
$user->update([‘updated_at’ => now()]);
复制代码您可以使用更快捷的方法:
u s e r > t o u c h ( ) ; u p d a t e d a t c o m m e n t p o s t u p d a t e d a t user->touch(); 复制代码另一种情况,有时候您不仅希望更新当前模型的updated_at,也希望更新上级关系的记录。 例如,某个comment被更新,那么您希望将post表的updated_at也更新。 那么,您需要在模型中定义 touches属性:
class Comment extends Model {

protected $touches = ['post'];

public function post()
{
    return $this->belongsTo('Post');
}

}
复制代码
8. 时间戳字段自动转换Carbon类
最后一个技巧,但更像是一个提醒,因为您应该已经知道它。
默认情况下,created_at和updated_at字段被自动转换为**$dates**,
所以您不需要将他们转换为Carbon实例,即可以使用Carbon的方法。
例如:
u s e r > c r e a t e d a t > a d d D a y s ( 3 ) ; n o w ( ) > d i f f I n D a y s ( user->created_at->addDays(3); now()->diffInDays( user->updated_at);

发布了124 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/a59612/article/details/104512774