我在下面有一个查询,用于检查用户是否喜欢彼此:
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 的查询生成器连接查询来获得它?
感谢您的输入,我终于这样做了,但是如果您有更好的解决方案,我仍然愿意接受。
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();
}