[英]Query with multiple select statment and join in Eloquent
I would like to know how the write below sql query in laravel 5.6 我想知道如何在laravel 5.6中写下面的sql查询
I have id coming from user $input = \\Auth::user()->id
我的ID来自用户
$input = \\Auth::user()->id
SELECT t1.*,
t2.*
FROM
(SELECT suggestions.*,
suggestions.id AS sug_id,
users.id AS users_id,
users.name AS user_name,
sum(votes.vote) AS total,
sum(CASE WHEN votes.vote = 1 THEN 1 ELSE 0 END) upvotes,
sum(CASE WHEN votes.vote = -1 THEN 1 ELSE 0 END) downvotes,
GROUP_CONCAT(votes.user_id) AS users_votes,
GROUP_CONCAT(votes.vote) AS votes_status
FROM users
JOIN suggestions ON users.id = suggestions.user_id
JOIN votes ON suggestions.id = votes.sug_id
WHERE suggestions.status = 1
GROUP BY suggestions.id
ORDER BY total DESC) AS t1
LEFT JOIN
(SELECT votes.user_id,
votes.vote AS vote_status,
suggestions.id AS sug_id
FROM votes
JOIN suggestions ON suggestions.id = votes.sug_id
WHERE votes.user_id = $input
GROUP BY sug_id
UNION SELECT '','','') AS t2 ON t1.sug_id = t2.sug_id
Here is my previous code, but I have no idea how to modify it with another select and join 这是我以前的代码,但是我不知道如何用另一个选择并加入来修改它
Suggestion::select('suggestions.*','suggestions.id as sug_id','users.id as users_id','users.name as user_name')
->addSelect(DB::raw('sum(votes.vote) as total'))
->addSelect(DB::raw('sum(case when votes.vote = 1 then 1 else 0 end) as upvotes'))
->addSelect(DB::raw('sum(case when votes.vote = -1 then 1 else 0 end) as downvotes'))
->addSelect(DB::raw('GROUP_CONCAT(votes.user_id) as users_votes'))
->addSelect(DB::raw('GROUP_CONCAT(votes.vote) as type_votes'))
->from('users')
->join('suggestions', function($join) {
$join->on('users.id', '=', 'suggestions.user_id');
})
->join('votes', function($join) {
$join->on('suggestions.id', '=', 'votes.sug_id');
})
->where('suggestions.status', '=', 1)
->groupBy('suggestions.id')
->orderByRaw('total DESC')
->get();
您必须分别引用表名和列名:
`t1.*` → `t1`.`*`
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.