Lloyd Banks
Lloyd Banks

Reputation: 36659

Laravel / Eloquent - Multiple Many to Many Relationships Using One Reference Table

I have a table that looks lie:

enter image description here

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

Answers (1)

Armin Sam
Armin Sam

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

Related Questions