0

我怎麼能在laravel 5.4自定義查詢在laravel 5

 select items.id,items.name,total,region from items LEFT OUTER JOIN 
    (select purchases.region_id as region , sum(purchases_detail.quantity) 
    as total,purchases_detail.item_id 
    from purchases_detail 
    left join purchases on(purchases.id=purchases_detail.purchase_id) 
    GROUP BY purchases_detail.item_id) pd on (pd.item_id=items.id) 

運行此類型的查詢時,我想這在DB ::選擇( '') 它給了我一個錯誤:

SQLSTATE [42000]:語法錯誤或訪問衝突:1055'amsdb.purchases.region_id'不在GROUP BY中(SQL:select items.id,items.name,total,來自項目的區域LEFT OUTER JOIN (select purchases.region_id as region,sum(purchases_detail.quantity)as total,purchases_detail.item_id f ROM purchases_detail 左連接上(pd.item_id = items.id))

上(purchases.id = purchases_detail.purchase_id) GROUP BY purchases_detail.item_id)PD購買,但它工作得很好,當我運行它的phpmyadmin

+1

你應該在Laravel中關閉strict,並且所有東西都會按照它的樣子工作。進入'config/database.php'並在mysql配置數組中,將'strict => true'改爲'strict => false'; – Maraboc

+0

@Maraboc不好的建議,他應該修復他的查詢。 –

+0

@TimBiegeleisen Ithink即使他修復了查詢,他應該更新嚴格模式! – Maraboc

回答

0

由於錯誤消息告訴您,purchases.region_id列不會顯示爲聚合,您也不會按它進行分組。快速的解決辦法是剛剛從內部和外部查詢中刪除此列:

SELECT 
    items.id, 
    items.name, 
    pd.total 
FROM items 
LEFT JOIN 
(
    SELECT 
     t1.item_id, 
     SUM(t1.quantity) AS total 
    FROM purchases_detail t1 
    LEFT JOIN purchases t2 
     ON t2.id = t1.purchase_id 
    GROUP BY t1.item_id 
) pd 
    ON pd.item_id = items.id 
0

不知道,但我認爲select()方法不能包含所有的SQL查詢。

我不知道它是否會工作,但試試這個。它使用了許多查詢生成器功能:

$subQuery = DB::table('purchases_detail') 
    ->select(DB::raw('purchases.region_id as region , sum(purchases_detail.quantity) 
    as total,purchases_detail.item_id')) 
    ->leftJoin('purchases', 'purchases.id', '=', 'purchases_detail.purchase_id') 
    ->groupBy('purchases_detail.item_id') 
    ->toSql(); 

$result = DB::table('items') 
    ->select('items.id', 'items.name', 'total,region') 
    ->leftJoin($subQuery . ' pd', 'pd.item_id', '=', 'items.id') // if not working, try ->leftJoin(DB::raw($subQuery) . ' pd', 'pd.item_id', '=', 'items.id') 
    ->get(); 

因爲你的查詢有一個嵌套SELECT,你必須讓它在兩次。