似乎无法将MySQL查询转换为Laravel Query Builder

时间:2015-01-17 17:43:58

标签: 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`

有什么想法吗?

1 个答案:

答案 0 :(得分: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();