Grouping Collection's Relationships together
Sorry, I'm not exactly sure how to title this question. I am making a booking platform where, a user can book an activity.
Each activity is available on custom set days, and each day has different time slots available, and each time slot as a limited number of spots.
A user can book only a single day at a time. In that booking they can select multiple time slots they want to book, and can select how many spots for each time slot they want to book.
To achieve this I have 3 models: Activity, Booking, BookingSpot
Relationships:
Activity->hasMany(Booking)
Booking->belongsTo(Activity)
Booking->hasMany(BookingSpot)
BookingSpot->belongsTo(Booking)
Booking has a field called date that determines what date the booking is for, and activity_id that determines what activity the user booked.
BookingSpot has a field called start_time and end_time (this is how I determine the time slot), and booking_id that determines what booking it belongs too.
I want to show a schedule for the activity. Showing each time slot that has bookings and the spots that have been booked.
Here is what I'm currently doing:
// Get all bookings for a particular day and group them by the Activity.
$query = Booking::select('*');
$date = date('Y-m-d', strtotime($date));
$queryDate = BookingSpot::select('booking_id');
$queryDate->where(DB::raw("date(start_time)"), '=', $date);
$bookingIdArray = $queryDate->orderBy('start_time', 'ASC')->get()->toArray();
$bookings = $query->whereIn('id', $bookingIdArray)->get()->groupBy('activity_id');
This returns all the bookings group by activity, but each booking could have multiple spots each with different start_time
How do I make a new collection from this that contains all the correct BookingSpots, that is grouped by start_time?
Edit: Here is a little chart to try to visually explain
userA, userB, userC, userD, userF all made a booking for March 24, 2019 for ACTIVITY
Here is what i am currently able to do
MARCH 24, 2019
ACTIVITY---|---userA-|-1:00PM
| |-1:00PM
| |-2:00PM
| |-2:00PM
|
|---userB-|-1:00PM
|
|---userC-|-1:00PM
| |-1:00PM
|
|---userD-|-2:00PM
|
|---userF-|-2:00PM
Here is what I want to accomplish
MARCH 24, 2019
ACTIVITY---|---1:00PM-|-userA
| |-userA
| |-userB
| |-userC
| |-userC
|
|---2:00PM-|-userA
|-userA
|-userD
|-userF
Please or to participate in this conversation.