Laravel数据库操作与用户认证授权全解析
1. 数据库操作
1.1 多对多的多态关系
在处理多对多的多态关系时,我们可以使用如下代码示例:
$contact = Contact::first();
$contact->tags->each(function ($tag) {
// Do stuff
});
$tag = Tag::first();
$tag->contacts->each(function ($contact) {
// Do stuff
});
1.2 子记录更新父记录时间戳
默认情况下,Eloquent模型会有 created_at
和 updated_at
时间戳。当相关项属于另一个项( belongsTo()
或 belongsToMany()
)时,我们可以通过在子模型类中添加 $touches
数组属性来标记父记录的更新。示例如下:
class PhoneNumber extends Model
{
protected $touches = ['contact'];
public function contact()
{
return $this->belongsTo(Contact::class);
}