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

标签 mysql 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 列,因为它在数据库上运行聚合函数。为避免这种情况,您可以只使用查询中定义的选择。正如@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();

关于mysql - 似乎无法将 MySQL 查询转换为 Laravel 查询生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28002332/

相关文章:

mysql - 如何在node.js中的mysql包中设置IF条件

Mysql - 在 "one to many"表中搜索

php - 如何GroupBy上组的最新记录

php - Laravel 多页面多语言路由

php - 根据用户 ID 和密码条件选择数据库

python - MySQL "Warning: Data truncated for column"仅出现在某些行上,即使它们与其他行的长度相同?

php - 使用 dropzone.js 和 laravel 5 验证CsrfToken

mysql - 到期日期为 7 天前,并且没有其他事件

CakePHP 3 : Nested SQL functions in a query

php - 多条件搜索查询生成器 [symfony2]