I wish to list a member with events he/she participates, and his/her collar numbers (idnumbers) for those events (one per event). Please see the attached diagram. This can be easily done with a simple SQL selection as:
select
m.name,
e.name,
n.number
from
members m
join participations p on p.member_id = m.id
join events e on e.id = p.event_id
left join idnumbers n on n.member_id = m.id and n.event_id = e.id
where
m.id = 1
order by
e.date,
e.title
In a model you basically need two parameters to access idnumbers; member and event. Whether you go on member model or event model, you need to pass a second parameter like:
$mymember->idnumbers($eventnumber)
or
$myevent->idnumbers($membernumber)
How can this be setup on eloquent so we can get the above list with eager loading?
Diagram: http://oi58.tinypic.com/oab50j.jpg
First off, why don't you create schema like this:
members: id, name
events: id, name
event_member (pivot table): id, member_id, event_id, number
Then simple relations:
// Member model
public function events()
{
return $this->belongsToMany('Event')->withPivot('number');
}
// Event model
public function members()
{
return $this->belongsToMany('Member')->withPivot('number');
}
Now you can access what you need as easily as this:
$member = Member::find($memberId);
$event = $member->events()->find($eventId);
$number = $event->pivot->number;
Same the other way around.
You can eager load the relations and access number
on all of the loaded models
Thank you Jarek, for a well made answer.
Actually I saw this coming =) The thing is this is a very simplified version of the problem. The tables are more crowded and one can exist without the other, they are seperated for schematic and permissional purposes.
This is solved using a pretty SQL query. Sometimes it's better not to dig too deep while the solution is right there =)
In this context; I found this approach useful when dealing with non standard Laravel eloquent relations:
// eager load my standard relations.
$myModel->load(array('relation1','relation2');
// set manual relation for my custom relation load.
$myModel->setRelation('custom_relation', $myModel->myCustomRelationFunction());
That way you can continue to rely on standard Eloquent functionality even when dealing with non standard relations.
Good tip Flightfreak. Haven't seen the 'setRelation' function before, I'll check it =)
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community