[ad_1]
A simplified version of my schema looks like this:
Events
Bookings
Participants
- participant_id
- booking_id
Users
Users are booked onto events via participant records, which belong to booking records, which are children of event records.
I am trying to write a method on the Event model to return all the users on the event, as an Eloquent relationship. I want it as Eloquent so I can chain where clauses etc., to further filter the resultset.
I have a participants() method on the Event model, that looks like this:
public function participants(): \Illuminate\Database\Eloquent\Relations\HasManyThrough
{
return $this->hasManyThrough(
Participant::class,
Booking::class,
'event_id',
'booking_id',
'participant_id',
'booking_id'
);
}
This works, and returns a HasManyThrough that I can traverse, or work with further.
My problem is in trying to create a users() method, without starting a new query builder.
I want to chain something to the participants() method, to get the User attached to each participant, and return this collection as an Eloquent relationship.
I realise I can do the following, but I end up with a simple array of objects this way, rather than a queryable Eloquent relationship. Which means I’ve lost the ORM functionality I want.
public function users()
{
$users = [];
foreach($this->participants as $participant){
$users[] = $participant->user;
}
return $users;
}
How would I go about turning my participants collection into users? Is it possible to build Eloquent relationships (or collections) ‘by hand’?
[ad_2]