Colin_Laws
2 years ago

Access Multiple Relationships On A Pivot Model Through A Model Using That Relationship

Posted 2 years ago by Colin_Laws

takes a deep breath yes, it's a lengthy title, I apologize!

I have a pivot table that joins three tables together: Users, Accounts, and Permissions.

The pivot table defines a user's access level to an account.

The individual permissions are not defined on the intermediate table because the permission table is related not only to the intermediate table between users and accounts, but also between another table that is irrelevant to this situation (I thought I would elaborate so that nobody would offer that as a solution).

What I need to do:

On the Account model, I define the relationship:


// ACCOUNT MODEL

public function users()
{
    return $this->belongsToMany('App\Models\Legacy\User', 'account_users', 'account_id', 'user_id')->withPivot('permission');

}

I want to add a method to the Account model that can filter the related users based on a property defined on the intermediate table's relationship to the permission table.

The permission table has a set of binary columns that dictate if a user is: an owner, billing admin, etc.

Something like this?


// ACCOUNT MODEL

public function owners()
{
    // The owner field exists on the permission table.
    // How do I access the pivot table's relationship to 
    // permissions right here?
    return users()->where('owner', true);
}

Please sign in or create an account to participate in this conversation.