【发布时间】: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