我有一个雄辩的查询,看起来像这样:
return $contest->join('posts','contests.id','posts.contest_id')
->join('winners', 'contests.winner_id', 'winners.id')
->where('posts.user_id', $id)
->where('winners.gold_user_id', $id)
->orWhere('winners.silver_user_id', $id)
->orWhere('winners.bronze_user_id', $id)
->orderBy('contests.created_at', 'desc');
在SQL中:
select * from `contests`
inner join `posts` on `contests`.`id` = `posts`.`contest_id`
inner join `winners` on `contests`.`winner_id` = `winners`.`id`
where `posts`.`user_id` = 4
and `winners`.`gold_user_id` = 4
or `winners`.`silver_user_id` = 4
or `winners`.`bronze_user_id` = 4
order by `contests`.`created_at` desc
但是我的问题是,它显示找到ID的所有其他比赛条目。
这是我的获胜者表:
我要检查的是用户是否是金牌,银牌或铜牌的赢家。现在,通过我的查询,它将选择ID行匹配的所有列。我该如何实现自己的目标?
答案 0 :(得分:1)
将OR conditions
放在括号中-如下所示
select * from `contests`
inner join `posts` on `contests`.`id` = `posts`.`contest_id`
inner join `winners` on `contests`.`winner_id` = `winners`.`id`
where `posts`.`user_id` = 4
and (`winners`.`gold_user_id` = 4
or `winners`.`silver_user_id` = 4
or `winners`.`bronze_user_id` = 4)
order by `contests`.`created_at` desc
OP ELOQUENT QUERY
return $contest->join('posts','contests.id','posts.contest_id')
->join('winners', 'contests.winner_id', 'winners.id')
->where('posts.user_id', $id)
->where(function($query) use ($id) {
$query->where('winners.gold_user_id', $id)
->orWhere('winners.silver_user_id', $id)
->orWhere('winners.bronze_user_id', $id);
})
->orderBy('contests.created_at', 'desc');