我有一张桌子:
事件[id,'name','areTicketsGenerated'],
Ticket ['id',event_id','seat_price_id','isAvailable'],
SeatPrice ['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票。
这应该可以获得所需的结果:
$data = Event::join('Ticket','Event.id','Ticket.event_id')
->join('SeatPrice','Ticket.seat_price_id','SeatPrice.id')
->select('Event.id as id','price_zone_id',DB::raw('count(Ticket.*) as Total'))
->where('isAvailable', true)
->groupby('Event.id','price_zone_id')
->get();
$events = $data->groupBy('id')->toarray();
现在你的刀片你应该能够:
@foreach($events as $key => $event)
{{$key}}
@foreach($event as $item)
{{$item['price_zone_id']}} - {{$item['Total']}}
@endforeach
@endforeach
你应该试试这个:
$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();