Laravel数据库与用户认证:深入解析与实践
1. 数据库操作与关系处理
1.1 向数据透视记录添加字段
在处理多对多关系时,有时需要向数据透视表添加额外的字段。以下是一个示例,展示了如何在 contacts 方法中添加 status 和 preferred_greeting 字段:
public function contacts()
{
return $this->belongsToMany(Contact::class)
->withTimestamps()
->withPivot('status', 'preferred_greeting');
}
当通过关系获取模型实例时,该实例会有一个 pivot 属性,代表其在数据透视表中的位置。例如:
$user = User::first();
$user->contacts->each(function ($contact) {
echo sprintf(
'Contact associated with this user at: %s',
$contact->pivot->created_at
);
});
1.2 多态关系
多态关系允许一个
超级会员免费看
订阅专栏 解锁全文
981

被折叠的 条评论
为什么被折叠?



