我感到有點困惑,我在查詢如何laravel轉換..怎麼我的MySQL查詢轉換在Laravel
select users.username,users.photo, questions.*,
(Select count(*) from answers
where answers.q_id=questions.id) as aAccount from questions
INNER JOIN users ON users.id=questions.user_id
我感到有點困惑,我在查詢如何laravel轉換..怎麼我的MySQL查詢轉換在Laravel
select users.username,users.photo, questions.*,
(Select count(*) from answers
where answers.q_id=questions.id) as aAccount from questions
INNER JOIN users ON users.id=questions.user_id
使用原始查詢
這些表達式將被注入到作爲查詢字符串,所以要小心不要創建任何SQL注入點!要創建原始表達式,你可以使用DB ::原始方法
DB::table('questions')
->join('users', 'users.id', '=', 'questions.user_id')
->select('users.username','users.photo', 'questions.*',
DB::raw("
( Select count(*) from answers
where answers.q_id=questions.id
)as 'aAccount'")
->get();
我upvoted JYoThl答案,因爲它正是我倒是擊穿此查詢到口若懸河,但在情況下在您洋洋灑灑查詢一部分變成原始的,我個人更喜歡保持整個sql原始。如果需要,您仍然可以向其中注入變量。
根據我的經驗,當您返回代碼重新讀取它時,將使用花費在規範化更復雜的查詢之後的時間量。
以下是您如何將原始格式的sql傳遞給您的方法。我也喜歡將數組轉換爲集合,因爲集合提供了多種方法。希望這可以幫助!
$questions = collect(DB::select(DB::raw("
select users.username,users.photo, questions.*,
(Select count(*) from answers where answers.q_id=questions.id) as aAccount
from questions
INNER JOIN users ON users.id=questions.user_id")
));
如果要注入變量,您可以將變量添加到數組()區域中。如果你想這樣做,你會做這樣的事情:
DB::select(DB::raw("select * from user where user = :user"), array('user' => $user))
使用原始查詢方法 – JYoThI
http://stackoverflow.com/questions/23826949/convert-sql-query-with-subquery-to-laravel-查詢。這可能有助於和是使用原始查詢@JYoThI建議 –
https://laravel.com/docs/5.4/queries使用Laravel的查詢生成器 –