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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments