1 回答

TA貢獻1921條經(jīng)驗 獲得超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 關注
- 172 瀏覽
添加回答
舉報