1. 禁用时间戳
如果数据表没有这两个字段,保存数据时 Model::create($arrayOfValues); —— 会看到 SQL error。Laravel 在自动填充 created_at / updated_at 的时候,无法找到这两个字段。
禁用自动填充时间戳,只需要在 Eloquent Model 添加上一个属性:
class Role extends Model
{
public $timestamps = FALSE;
// ... 其他的属性和方法
}
2.字段不一样,采用这样的方式进行设置
const CREATED_AT = 'create_time';
const UPDATED_AT = 'update_time';
3.修改时间戳日期 / 时间格式
默认情况下,时间戳自动格式为 '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
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()]);
您可以使用更快捷的方法:
$user->touch();