douyi3676 2018-03-03 12:08
浏览 90

查询多个select语句并加入Eloquent

I would like to know how the write below sql query in laravel 5.6

I have id coming from user $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();
  • 写回答

1条回答 默认 最新

  • duanliexi1052 2018-03-14 15:10
    关注

    You have to quote table and column names separately:

    `t1.*` → `t1`.`*`
    
    评论

报告相同问题?