Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

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

Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0

This is solved using a pretty SQL query. Sometimes it's better not to dig too deep while the solution is right there =)

Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0

Good tip Flightfreak. Haven't seen the 'setRelation' function before, I'll check it =)

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

DeadDuck deadduck Joined 25 Mar 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.