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`
任何想法?
如果一切都失敗了,您可以使用原始查詢。沒有聲明您需要使用查詢構建器。 –
是的,但我更喜歡使用查詢生成器(因爲它的SQL注入保護,因爲我想了解)。 – atwright147
你正在使用 - >加入而不是 - >左加入你的照明查詢 – baao