1 回答

TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊
比方說,你有這兩種型號(hào):User與Role這使得許多一對(duì)多的關(guān)系。
如果你正確定義了你的關(guān)系:
/** User.php */
public function roles()
{
return $this->belongsToMany(Role::class);
}
——
/** Role.php */
public function users()
{
return $this->belongsToMany(User::class);
}
然后你可以使用這種關(guān)系來完成你想要做的事情。
從相關(guān)對(duì)象:
$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();
此外,您可以使用返回關(guān)系的集合實(shí)例找到所需的相關(guān)模型:
$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 關(guān)注
- 177 瀏覽
添加回答
舉報(bào)