我在下面有一个查询,用于检查用户是否彼此喜欢:
SELECT a.user_id, a.target_id
FROM user_nices a
INNER JOIN user_nices b
ON a.user_id = b.target_id AND b.user_id = a.target_id
我还有一个users
表,用于存储用户信息。我也想获得他们的信息。我创建了一个模态函数,其中id
代表当前用户ID。
public function getMatches($id){
return \DB::table('user_nices')
->join("user_nices as b", function($q){
$q->on("user_nices.user_id", "=", "b.target_id");
$q->on("b.user_id", "=", "user_nices.target_id");
})
->get();
}
我的代码现在可以检索数据,但不包含用户信息,并且还应该仅返回用户的匹配用户。 我如何使用Laravel的查询构建器联接查询来实现?
答案 0 :(得分:0)
感谢您的投入,我终于以这种方式做到了,但是,如果您有更好的解决方案,我仍然愿意接受。
public function getMatchPeople($uid)
{
return \DB::table('user_nices')
->join("user_nices as b", function($q){
$q->on("user_nices.user_id", "=", "b.target_id");
$q->on("b.user_id", "=", "user_nices.target_id");
})
->join('users', function($q){
$q->on('users.id',"=", "user_nices.target_id");
})
//to only get users details who likes current user
->where("user_nices.user_id", '=', $uid)
->where("user_nices.target_id", '!=', $uid)
->selectRaw("user_nices.user_id as user_id, users.name as name,
user_nices.id as id, users.email as email, users.nickname as nickname ,user_nices.created_at as create_at")
->get();
}