使用自定义原始选择

时间:2018-03-04 12:30:38

标签: mysql laravel eloquent query-builder laravel-query-builder

我试图让这个sql代码在原始查询中工作,但它仍然返回以下错误

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax;
  check the manual that corresponds to your MariaDB server version for the right syntax to use
  near '.`*,suggestions`.`id` as `sug_id,users.id` from `suggestions`' at line 1  
(SQL: select `SELECT t1`.`*, t2`.`* from (select suggestions`.`*,suggestions`.`id` as `sug_id,users.id` from `suggestions`)

对于已登录的用户$input = \Auth::user()->id

,我有来自Auth的用户ID

SQL代码:

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') AS t2 ON t1.sug_id = t2.sug_id

Laravel功能:

$suggestions = Suggestion::select('sql_code')
    ->get();
    return view('głosuj', [
       'suggestions' => $suggestions
     ]);
     }
}

0 个答案:

没有答案