【问题标题】:Can't seem to translate the MySQL query to Laravel Query Builder似乎无法将 MySQL 查询转换为 Laravel Query Builder
【发布时间】:2015-03-16 03:25:01
【问题描述】:

我一直在尝试将以下 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`

有什么想法吗?

【问题讨论】:

  • 如果一切都失败了,您可以只使用原始查询。没有说明您需要使用查询生成器。
  • 是的,但我更喜欢使用查询生成器(因为它是 SQL 注入保护并且因为我想了解)。
  • 您在照明查询中使用 ->join 而不是 ->leftJoin
  • @michael 非常正确。我纠正了这一点,它有所帮助。

标签: mysql laravel query-builder


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-04-10
    • 1970-01-01
    • 2019-02-12
    • 2014-05-30
    • 2021-02-04
    • 2018-09-13
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    相关资源
    最近更新 更多