我想检查两个用户是否有这些相同的关系。我有型号:{"type":"string"}
和root
。
用户关系:
STRING
团队关系:
User
因此,用户可以成为少数团队的一部分。如何检查2个指定用户是否有共同团队?
答案 0 :(得分:1)
假设您将模型视为Eloquent Collections,有几种方法可供您实现。
一个选项是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() );
答案 1 :(得分: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
答案 2 :(得分:0)
我无法用口才帮助你,但我可以用原始查询来帮助你。考虑到您的表名为users和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中的值更好。