I have been trying to translate the following MySQL query into Laravel Query Builder. Could anyone suggest how to get this working?
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
Here is my current code:
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');
}
In contrast to the query I want to execute, I get the following:
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`
Any ideas?