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