首页 > 解决方案 > 按相关表中的字段对数据进行分组

问题描述

我有一张桌子:

事件[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 门票。

标签: laravel

解决方案


你应该试试这个:

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

推荐阅读