Я пытался перевести следующий запрос 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`
Любые идеи?