Laravel中rightJoin无法正常工作,附现有关联查询代码求助
解决Laravel中rightJoin无法正常工作的问题
我来帮你排查下这个问题,结合你实现好友请求的代码来分析:
先理清原代码的逻辑
你当前用leftJoin的写法是没问题的:从friendships表出发,关联请求者的users数据,筛选出发给当前用户的未处理好友请求,这个逻辑完全贴合你的需求:
public function requests() { $uid = Auth::user()->id; $FriendRequests = DB::table('friendships') ->leftJoin('users', 'users.id', '=', 'friendships.requester') ->where('status', '=', Null) ->where('friendships.user_requested', '=', $uid)->get(); return view('profile.requests', compact('FriendRequests')); }
为什么换成rightJoin就不行?
rightJoin的逻辑是把右侧表(这里是users)作为主表,会返回右侧表的所有记录,再匹配左侧表(friendships)的关联数据。但你的where条件里加了friendships.user_requested = $uid和status = Null,这会导致:
- 只有那些给当前用户发过未处理请求的用户会被保留
- 其他用户因为
friendships相关字段都是null,会被where条件直接过滤掉,最终结果和innerJoin一模一样,完全达不到你想要的效果
正确的处理方式
如果你的需求还是获取发给当前用户的未处理好友请求,leftJoin其实是最贴合业务逻辑的选择——毕竟你是从好友请求记录出发,去关联请求者的信息,没必要强行用rightJoin。
但如果你确实想尝试用rightJoin实现相同功能,需要把friendships的条件放到关联规则里,而不是where子句中:
public function requests() { $uid = Auth::user()->id; $FriendRequests = DB::table('friendships') ->rightJoin('users', function($join) use ($uid) { $join->on('users.id', '=', 'friendships.requester') ->where('friendships.status', '=', null) ->where('friendships.user_requested', '=', $uid); }) ->whereNotNull('friendships.id') // 过滤掉没有对应好友请求的用户记录 ->get(); return view('profile.requests', compact('FriendRequests')); }
另外,建议你检查下friendships表的结构:比如status字段是不是用null表示未处理?如果是用0或者其他值标记未处理,那你的where('status', '=', Null)就得调整成对应的值。
内容的提问来源于stack exchange,提问作者Biswas Sampad
相关产品推荐
相关产品推荐

