2014-06-27 94 views
0

我已閱讀Laravel文檔,但我無法完成這一項工作。Laravel中的Complex-ish查詢(雄辯)

有誰知道這個查詢是否可能在Eloquent?

如果是這樣,你會如何寫它?

SELECT 

MONTHNAME(postdate) as monthname, 
DATE_FORMAT(postdate,'%m') as month, 
YEAR(postdate) as year, 
COUNT(MONTHNAME(postdate)) as num 

FROM 
postData 

WHERE 
status = 1 

GROUP BY 
monthname, 
year 

ORDER BY 
postdate DESC 
+0

是否有一個原因,不只是使用DB :: raw()或selectRaw()這個?只是好奇 – KyleK

+0

@KyleK我猜如果他問這樣的問題而不提這可能是因爲他不知道'DB :: raw'或'selectRaw'。 – rmobis

+0

嗯......我不確定,因爲他特意將(雄辯)放在括號中,所以我想也許他特別想要一個雄辯/流利的版本 – KyleK

回答

3

雖然簡單地使用DB::raw整個查詢工作,它不覺得我的權利。您可能想使用查詢生成器來嘗試此解決方案。

DB::table('postData')->select([ 
    DB::raw('MONTHNAME(postdate) AS monthname'), 
    DB::raw('DATE_FORMAT(postdate, \'%m\') AS month'), 
    DB::raw('YEAR(postdate) AS year'), 
    DB::raw('COUNT(MONTHNAME(postdate)) AS num'), 
])->where('status', 1) 
    ->groupBy('monthname', 'year') 
    ->orderBy('postdate', 'DESC'); 

它仍然使用DB::raw,但僅限於select子句。無論如何,你可以使用PostData模型,而不是DB::table('postData'),但由於它實際上不會是常規的PostData對象,所以我建議不要這樣做。

+0

這就是我以後的感謝。請問PostData對象是什麼意思?我的意圖是開始這樣的查詢:$ posts = $ this-> posts-> select([... – user1894292

+1

]哦,你通過另一個模型訪問關係。你看,每當我有一個模型,我希望它有如果我返回'PostData',我希望它有一個'postdate'和'status'屬性,而不是你使用AS子句指定的定製屬性 PS :如果你真的把它當作一個關係,記得你真的要做'$ this-> posts() - > select(...'。注意'posts()'而不是'posts'。這是由於Laravel如何處理魔法屬性。 – rmobis

+0

謝謝拉斐爾。我讚賞詳細的解釋。 – user1894292

2

如果你不介意使用DB ::原始()只是這樣做......

易複製......

DB ::選擇(DB ::原始(」 SELECT MONTHNAME(postdate)as monthname,DATE_FORMAT(postdate,'%m')as month, YEAR(postdate)as year,COUNT(MONTHNAME(postdate))as num FROM postData WHERE status = 1 GROUP BY monthname,year ORDER BY postdate DESC「));

一號線......

DB::select(DB::raw("SELECT MONTHNAME(postdate) as monthname, DATE_FORMAT(postdate,'%m') as month,YEAR(postdate) as year, COUNT(MONTHNAME(postdate)) as num FROM postData WHERE status = 1 GROUP BYmonthname,year ORDER BY postdate DESC")); 
+0

忘記在查詢周圍添加''' – rmobis

+0

哎呀......好的眼睛:) – KyleK

+0

謝謝KyleK。是啊,我不知道如何正確使用DB :: raw。 – user1894292