2015-01-17 46 views
1

我一直在嘗試將以下MySQL查詢翻譯成Laravel Query Builder。任何人都可以建議如何使這個工作?似乎無法將MySQL查詢翻譯成Laravel Query Builder

SELECT 
orders.id AS order_id, 
COUNT(products.id) AS count 
FROM 
order_product 
LEFT JOIN orders ON orders.id = order_product.order_id 
LEFT JOIN products ON order_product.product_id = products.id 
WHERE 
orders.user_id = 2 
GROUP BY 
orders.id 

這裏是我當前的代碼:

public static function getProductsCount($userId = null) 
{ 
    if (!is_numeric($userId)) { 
     return false; 
    } 
    DB::table('order_product') 
     ->join('orders', 'orders.id', '=', 'order_product.order_id') 
     ->join('products', 'order_product.product_id', '=', 'products.id') 
     #->select('orders.id AS orders_id') 
     ->where('orders.user_id', '=', $userId) 
     ->distinct('products.id') 
     ->groupBy('orders.id') 
     ->count('products.id'); 
} 

相反我要執行查詢,我得到如下:

select count(distinct `products`.`id`) as aggregate from `order_product` inner join `orders` on `orders`.`id` = `order_product`.`order_id` inner join `products` on `order_product`.`product_id` = `products`.`id` where `orders`.`user_id` = ? group by `orders`.`id` 

任何想法?

+0

如果一切都失敗了,您可以使用原始查詢。沒有聲明您需要使用查詢構建器。 –

+0

是的,但我更喜歡使用查詢生成器(因爲它的SQL注入保護,因爲我想了解)。 – atwright147

+3

你正在使用 - >加入而不是 - >左加入你的照明查詢 – baao

回答

1

count方法臨時覆蓋指定的select列,因爲它在數據庫上運行聚合函數。爲了避免這種情況,您可以使用查詢中定義的select。同樣@michael在評論中指出,你應該使用leftJoin而不是join。以下將生成您發佈的確切查詢:

DB::table('order_product') 
     ->leftJoin('orders', 'orders.id', '=', 'order_product.order_id') 
     ->leftJoin('products', 'order_product.product_id', '=', 'products.id') 
     ->select('orders.id AS orders_id', 'COUNT(products.id) AS count') 
     ->where('orders.user_id', '=', $userId) 
     ->groupBy('orders.id') 
     ->get();