laravel - 按相关表中的字段对数据进行分组
问题描述
我有一张桌子:
事件[id, 'name', 'areTicketsGenerated'],
票 ['id', event_id', 'seat_price_id', 'isAvailable'],
座位价格['id', 'price_zone_id']。
我需要接收所有事件。在每个事件中,我需要计算按“price_zone_id”分组的可用门票。
我的查询是下一个:
$events = Event::with([
'tickets',
'tickets.seatPrice',
])->where('areTicketsGenerated', true)
->get();
foreach($events as $event) {
$ticketsCount = $event->tickets->where('isAvailable', true) ...
}
但我只收到了所有可用的门票。
如何按“price_zone_id”分组?
例如:
事件1
价格区 1 - 10 门票;
价格区 2 - 50 张门票。
事件2
价格区 4 - 20 张门票;
价格区 5 - 25 门票。
解决方案
你应该试试这个:
$events = Event::with([
'tickets',
'tickets.seatPrice' => function($query){
$query->groupBy('price_zone_id');
}])
->where('areTicketsGenerated', true)
->get();
更新的答案
也使用流利的查询
use DB;
$events = DB::table('events')
->join('tickets', 'tickets.event_id', '=', 'events.id')
->leftJoin('seat_price', 'tickets.seat_price_id', '=', 'seat_price.id')
->where('events.areTicketsGenerated',true)
->groupBy('seat_price.price_zone_id')
->get();
推荐阅读
- python - 我可以像在组中一样创建和处理不在组中的 pygame 精灵吗?
- python - Django个性化网址
- scala - 在数据集元素中执行“非转换”操作的最佳方法是什么
- azure - 删除多个 Azure 数据工厂管道
- mysql - Mysql通过自动增量主键选择,同时按日期分区
- ruby-on-rails - 在选择标签 haml ruby 和 rails 中显示名称和 ID
- r - 如何使用从欧洲防风草函数 boost_tree 渲染的“_xgb.Booster”“model_fit”对象计算提升曲线和十分位数提升图表?
- javascript - 倒数计时器 - 在页面中使用多次
- c# - 事件溯源 - 说明何时将事件添加到事件存储
- java - RestTemplate 尝试捕获