2016-09-14 44 views
0

以雄辯的方式做我的第一步,我試圖實現一個查詢來檢索一些數據並同時計算一些條件。在同一個查詢中雄辯地多次選擇

此生SQL語句按預期工作

SELECT * 
FROM photos, 
(SELECT COUNT(*) FROM photos where type = 1 and published =1 group by type) as qA, 
(SELECT COUNT(*) FROM photos where type = 2 and published =1 group by type) as qP 
where product_id = 7 
and published = 1 

但使用照片模式,我不能得到相同的結果

Photo::select(*, 
Photo::raw('count(*) where type = 1 and published =1 group by type as qA), 
Photo::raw('count(*) where type = 2 and published =1 group by type as qP)) 
->where ('product_id',7) 
->where('published', 1) 
->get() 

剔除「原始」的句子,這個查詢工作,但我需要計算這些「類型」出現次數。

在此先感謝您的任何指導。

+0

嘗試寫 - > toSql()來代替 - > get()方法,你會打印出什麼是SQL等同。然後,您可以根據需要進行更改(每當我需要返工查詢時,我都會進行解決) – abr

回答

0

你真的需要在一個查詢中獲得所有內容嗎?它對你的應用程序有意義嗎?我的意思是,我猜這些類型數並不是關於您正在提取的記錄(s?)的真實信息(product_id = 7),而是它們是關於整個表的狀態的一般信息。

如果這是有道理的,你可以嘗試

$photo = Photo::where ('product_id',7) 
    ->where('published', 1) 
    ->get(); 

$types_count = Photo::where('published', 1) 
    ->selectRaw('type, COUNT(*) AS count') 
    ->groupBy('type') 
    ->get() 
    ->keyBy('type'); 

$qA = $types_count[1]->count; 
$qP = $types_count[2]->count;