2016-04-26 76 views
1

我想檢查兩個用戶是否有這些相同的關係。我有型號:UserTeamLaravel檢查用戶是否有相同的關係

用戶關係:

public function teams() 
    { 
     return $this->belongsToMany('App\Team'); 
    } 

團隊關係:

public function users() 
    { 
     return $this->belongsToMany('App\User'); 
    } 

這樣用戶就可以少隊的一部分。如何檢查2個指定用戶是否有共同的團隊?

回答

0

怎麼樣在嵌套循環由名檢查,像這樣:

$user1 = User::find(1); 
$user2 = User::find(2); 

foreach($user1->teams->name as $team1) 
    foreach($user2->teams->name as $team2) 
     if($team1 == $team2) 
     //do awesome stuff 

以上將無法正常工作。正確的代碼(由Filip Koblański的建議):

$user1 = User::find(1); 
$user2 = User::find(2); 

foreach($user1->teams as $team1) 
    foreach($user2->teams as $team2) 
     if($team1->name == $team2->name) 
     //do awesome stuff 
0

我不能幫你口才好,但我可以幫你用原始查詢。考慮到你的表被稱爲用戶和team_memberships(你的多對多表存儲成員),你可以做一個像這樣的原始查詢。

function checkCommonTeams($user_id_A, $user_id_B){ 
$common = DB::select(
    DB::raw(
    'SELECT users.*,teams.* FROM users as user_A 
    INNER JOIN team_memberships as teams ON user_A.id = teams.member_id 
    INNER JOIN team_memberships as teams_B ON teams_B.id = teams.id 
    WHERE teams_B.member_id = :user_B AND users.id = :user_A LIMIT 1' 
), 
    ['user_A' => $user_id_A, 'user_B' => $user_id_B] 
); 
return (!count($common)) ? false : true; 
} 

像這樣的東西應該工作以及執行查詢比兩個用戶的團隊和對每個值等檢查你只要你的數據庫是如何組織的檢查自己的方式更快。

如果他們共享團隊,這將返回true或false。

我的理念是,如果你可以在你的數據庫中做這樣的事情,那麼試着去做,因爲它應該幾乎總能比多重查詢和比較php中的值做得更好。

1

假設您將模型視爲雄辯集合,有幾種方法可以實現這一點。

一種選擇是intersect(更多在這裏:https://laravel.com/docs/5.2/collections#method-intersect

$user = User::with('teams') -> find($id); 
$userCompare = User::with('teams') -> find($idCompare); 

dump($user -> teams -> intersect($userCompare -> teams) -> count());