php 使用 Eloquent 实现 group_by 并在 Laravel 中拥有
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16976241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implementing group_by and having in Laravel using Eloquent
提问by howellmartinez
I am having trouble implementing the group_by and having queries using Eloquent in Laravel.
我在实现 group_by 和在 Laravel 中使用 Eloquent 进行查询时遇到问题。
Here is the scenario:
这是场景:
orders
- id
- qty
deliveries
- id
- qty
- order_id
I want to use a join to display the orders with incomplete deliveries as well as the corresponging balance:
我想使用连接来显示交货不完整的订单以及相应的余额:
Order::left_join('deliveries', 'orders.id', '=', 'deliveries.order_id')
->select(array('orders.*'), DB::raw('orders.qty - IFNULL(sum(deliveries.qty),0) AS balance')))
->group_by('order_id')
->having('balance', '>', 0)
->get();
The 'balance' value works fine without the 'having' clause. On adding the 'having' clause however, the resulting table doesn't display any rows. Does anyone have any ideas?
'balance' 值在没有 'have' 子句的情况下工作正常。但是,在添加 'have' 子句时,结果表不显示任何行。有没有人有任何想法?
Thanks in advance!
提前致谢!
回答by howellmartinez
Ended up switching to Laravel 4 and doing the ff which seemed to work.
最终切换到 Laravel 4 并执行似乎有效的 ff。
Order::leftJoin('deliveries', 'orders.id', '=', 'deliveries.order_id')
->select(array('orders.*'), DB::raw('orders.qty - IFNULL(sum(deliveries.qty),0) AS balance')))
->groupBy('order_id')
->havingRaw('balance > 0')
->get();