似乎无法将 MySQL 查询转换为 Laravel 查询生成器

Can't seem to translate the MySQL query to Laravel Query Builder

我一直在尝试将以下 MySQL 查询翻译成 Laravel 查询生成器。谁能建议如何让它工作?

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`

有什么想法吗?

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();