I'm working on a project that has a many to many relationship between User
and Club
. This relationship works and I can get the respective objects with: $user->clubs
. The pivot table I've named memberships
. I can get the pivot data with $club->pivot
. Foreign keys are defined for the memberships
table in migrations.
However, I'd like the pivot table to be represented by a model so that I can easily update attributes of Membership
such as role (Or even add a Role
model to Membership
!) or status
.
I've looked at "Defining A Custom Pivot Model" in the docs, but what it says doesn't work for me, I get:
ErrorException
Argument 1 passed to Illuminate\Database\Eloquent\Model::__construct() must be of the type array, object given
I've also looked at this description of how to do it, but it's more or less the same as above.
Membership
model:
class Membership extends Eloquent {
protected $table = 'memberships';
public function user()
{
return $this->belongsTo('User');
}
public function club()
{
return $this->belongsTo('Club');
}
}
Has anyone done this before?
This has been solved by a suggestion by a reddit user to extend Pivot
in my Membership model. I also had to add ->withPivot('status', 'role')->withTimestamps()
to the relationship declarations in the User and Club models.
You can do this by adding some manual code.
Your Membership model looks ok. You can get all clubs of a $user easily if you define method $user->clubs() where you get all the clubs manually.
clubs() {
$memberships=$this->memberships;
$clubs=new \Illuminate\Database\Eloquent\Collection();
foreach($memberships as $m) {
$clubs=$clubs->merge($m->clubs);
}
return $clubs;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With