我有一个场景,我想找到正在关注用户 X 且用户 X 正在关注他们的用户。
查看以下架构: 带有测试值的数据库表
我们有follower_id和following_id, 现在假设我们要检查 id 23 的用户是否正在关注某人并且他们也正在关注他。
如您所见,用户 22 正在关注用户 23, 所以我们想从用户表中获取用户 22 的详细信息,例如姓名和电子邮件。
用户 23 正在关注 24,但用户 24 没有关注用户 23,因此我们不会将用户 24 包含在我们的列表中。
请帮我编写查询以获取上述场景的用户列表。 谢谢
更新
因为我需要有关用户的更多信息。我现在正在 Laravel 中实现一个缓慢的解决方案。
$UsersIAmFollowing = UserFollowing::where('follower_id', $user->id)->get();
$UsersFollowingMe = UserFollowing::where('following_id', $user->id)->get();
$friends = [];
foreach ($UsersIAmFollowing as $userIamFollowing) {
foreach ($UsersFollowingMe as $userFollowingMe) {
if($userIamFollowing->following_id == $userFollowingMe->follower_id){
array_push($friends, User::find($userIamFollowing->following_id));
}
}
}
dd($friends);
select t.id
,t.follower_id
,t.following_id
from t join t t2 on t2.following_id = t.follower_id
and t.following_id = t2.follower_id
id | follow_id | 以下_id |
---|---|---|
7 | 22 | 23 |
6 | 23 | 22 |