2017-12-27 412 views
2

我有一个多对多的关系:laravel检查,如果集合包含模型

users (id) 

user_game (user_id, game_id) 

games (id, title) 

我要检查,如果一个游戏关联到一个特定的用户:

$user = User::find(1); 
$game = Game::where('title', 'pacman'); 

$gameUsers = $game->users() 
$gameHasUser = >>> $gameUsers contains $user <<< // How can I do this? 

回答

1

对于许多一对多你可以使用contains()方法:

$game = Game::where('title', 'pacman')->first(); 
if ($game->users->contains($userId)) { 
    // Do something. 
} 
0

您可以使用where子句中用户的游戏列表来查看是否存在游戏:

$user = User::find(1); 
$gameHasUser = $user->games()->where('title', 'pacman')->isNotEmpty();