1 回答
TA贡献1921条经验 获得超9个赞
比方说,你有这两种型号:User与Role这使得许多一对多的关系。
如果你正确定义了你的关系:
/** User.php */
public function roles()
{
return $this->belongsToMany(Role::class);
}
——
/** Role.php */
public function users()
{
return $this->belongsToMany(User::class);
}
然后你可以使用这种关系来完成你想要做的事情。
从相关对象:
$user = User::find(1);
// getting all the roles attached with a user:
$roles = $user->roles;
// getting all the roles attached with a user that has certain ids:
$roles = $user->roles()->whereIn('id', [2, 4, 6])->get();
此外,您可以使用返回关系的集合实例找到所需的相关模型:
$user = User::find(1);
// getting all the roles attached with a user:
$roles = $user->roles;
// getting a specific role attached to a user:
$specific_role = $roles->where('id', 6)->first();
- 1 回答
- 0 关注
- 156 浏览
添加回答
举报