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

1,354次阅读
没有评论

默认情况下,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;

// ... 其他的属性和方法

}

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

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

  1. 修改时间戳日期 / 时间格式
    以下内容引用官网文档 official Laravel documentation:

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

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

  1. 多对多:带时间戳的中间表
    当在多对多的关联中,时间戳不会自动填充,例如 用户表  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();
}

  1. 使用 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();

  1. 不触发 updated_at 的修改
    无论何时,当修改 Eloquent 记录,都将会自动使用当前时间戳来维护 updated_at 字段,这是个非常棒的特性。

但是有时候你却不想这么做,例如:当增加某个值,认为这不是 “整行更新”。

那么,你可以一切如上 —— 只需禁用 timestamps,记住这是临时的:

$user = User::find(1);
$user->profile_views_count = 123;
$user->timestamps = false;
$user->save();

  1. 仅更新时间戳和关联时间戳
    与上一个例子恰好相反,也许您需要仅更新 updated_at 字段,而不改变其他列。

所以,不建议下面这种写法:

$user->update([‘updated_at’ => now()]);
您可以使用更快捷的方法:

$user->touch();
另一种情况,有时候您不仅希望更新当前模型的 updated_at,也希望更新上级关系的记录。

例如,某个 comment 被更新,那么您希望将 post 表的 updated_at 也更新。

那么,您需要在模型中定义 $touches 属性:

class Comment extends Model {

protected $touches = ['post'];

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

}

  1. 时间戳字段自动转换 Carbon 类
    最后一个技巧,但更像是一个提醒,因为您应该已经知道它。

默认情况下,created_at 和 updated_at 字段被自动转换为 $dates,
所以您不需要将他们转换为 Carbon 实例,即可以使用 Carbon 的方法。

例如:

$user->created_at->addDays(3);
now()->diffInDays($user->updated_at);

正文完
可以使用微信扫码关注公众号(ID:xzluomor)
post-qrcode
 0
评论(没有评论)

文心AIGC

2024 年 11 月
 123
45678910
11121314151617
18192021222324
252627282930  
文心AIGC
文心AIGC
人工智能ChatGPT,AIGC指利用人工智能技术来生成内容,其中包括文字、语音、代码、图像、视频、机器人动作等等。被认为是继PGC、UGC之后的新型内容创作方式。AIGC作为元宇宙的新方向,近几年迭代速度呈现指数级爆发,谷歌、Meta、百度等平台型巨头持续布局
文章搜索
热门文章
清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开

清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开

清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开 Jay 2026-01-08 20:18:...
训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享

训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享

训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享 衡宇 2026-01-08 20:...
「北京版幻方」冷不丁开源SOTA代码大模型!一张3090就能跑,40B参数掀翻Opus-4.5和GPT-5.2

「北京版幻方」冷不丁开源SOTA代码大模型!一张3090就能跑,40B参数掀翻Opus-4.5和GPT-5.2

「北京版幻方」冷不丁开源SOTA代码大模型!一张3090就能跑,40B参数掀翻Opus-4.5和GPT-5.2...
AI金矿上打盹的小红书,刚刚醒了一「点点」

AI金矿上打盹的小红书,刚刚醒了一「点点」

AI金矿上打盹的小红书,刚刚醒了一「点点」 鱼羊 2025-12-26 17:04:08 来源:量子位 一个积...
最新评论
ufabet ufabet มีเกมให้เลือกเล่นมากมาย: เกมเดิมพันหลากหลาย ครบทุกค่ายดัง
tornado crypto mixer tornado crypto mixer Discover the power of privacy with TornadoCash! Learn how this decentralized mixer ensures your transactions remain confidential.
ดูบอลสด ดูบอลสด Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
Obrazy Sztuka Nowoczesna Obrazy Sztuka Nowoczesna Thank you for this wonderful contribution to the topic. Your ability to explain complex ideas simply is admirable.
ufabet ufabet Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
ufabet ufabet You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!
ufabet ufabet Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
热评文章
海信CES发布全新一代RGB-Mini LED,全球首创玲珑4芯真彩背光

海信CES发布全新一代RGB-Mini LED,全球首创玲珑4芯真彩背光

海信CES发布全新一代RGB-Mini LED,全球首创玲珑4芯真彩背光 量子位的朋友们 2026-01-06...
英特尔CES奇袭老黄大本营!英伟达显卡刚涨价,最强酷睿量产出货

英特尔CES奇袭老黄大本营!英伟达显卡刚涨价,最强酷睿量产出货

英特尔CES奇袭老黄大本营!英伟达显卡刚涨价,最强酷睿量产出货 十三 2026-01-06 13:54:54 ...
陈天桥代季峰打响2026大模型第一枪:30B参数跑出1T性能

陈天桥代季峰打响2026大模型第一枪:30B参数跑出1T性能

陈天桥代季峰打响2026大模型第一枪:30B参数跑出1T性能 鹭羽 2026-01-06 14:28:58 来...
OpenAI推理第一人离职,7年打造了o3/o1/GPT-4/Codex

OpenAI推理第一人离职,7年打造了o3/o1/GPT-4/Codex

OpenAI推理第一人离职,7年打造了o3/o1/GPT-4/Codex 衡宇 2026-01-06 13:0...