Reputation: 36659
I have a table that looks lie:
The table serves as a reference table between two tables. The kicker is that the second table this reference table serves depends on the value of member_type
.
There are three tables being connected using the above table: incidents
, user_member_incidents
, and server_member_incidents
. The member_id
column in the reference table references either the user_member_incidents
table or the server_member_incidents
table. This is determined by the value of the member_type
column.
How would I reflect this relationship using a belongsToMany
method in Eloquent?
Upvotes: 0
Views: 683
Reputation: 933
Assuming that you have Incident
, UserMember
, and ServerMember
models, you can define the following relationships:
class Incident extends Model
{
public function userMember()
{
return $this->belongsToMany(
UserMember::class,
'your_pivot_table_name',
'incident_id',
'member_id'
)->wherePivot('member_type', 1);
}
public function serverMember()
{
return $this->belongsToMany(
ServerMember::class,
'your_pivot_table_name',
'incident_id',
'member_id'
)->wherePivot('member_type', 2);
}
}
Hope this answers your question.
Upvotes: 4