skip to Main Content

I have a drinks table and a suppliers table, there is a many to many relationship between them, with a drink_supplier table.

The drink_supplier table has an extra field on it called role. This is a FK, to a roles table. The roles table has a title field on it.

In Laravel, I wish to write a constrained relationship on the Drink model so that I can get the suppliers of the drink but when the supplier acted in a certain role.

Drinks

id| title
1 | Cola

Suppliers

id| title     |
1 | Acme Inc. | 

Roles

id| title
1 | Producer
2 | Reseller

Drink Supplier

drink_id | supplier_id | role_id
1        | 1           | 2

Drink Model:

public function suppliers(): BelongsToMany {
    return $this->belongsToMany(Suppliers::class)
}

public function resellers(): BelongsToMany
{
     return $this->suppliers()->wherePivot('supplier_role_id', 2);
}

The above is fine, but I want to be able to amend the resellers relationship, so instead of passing an int I can pass the string Reseller.

How can I do this inside of the relationship definition?

2

Answers


  1. Rather than dealing with pivot tables, just use Laravel’s built-in methods for dealing with relationships.

    Assuming your Suppliers model has the correct roles() relationship method in place, I think this will work:

    public function suppliers(): BelongsToMany
    {
        return $this->belongsToMany(Suppliers::class);
    }
    
    public function resellers(): BelongsToMany
    {
        return $this
            ->suppliers()
            ->whereRelation('roles', 'title', 'Reseller');
    }
    
    Login or Signup to reply.
  2. still not shure if I got your question right but if I do it might be as simple as ditching the roles table and make role_id a string (and rename it to role).

    Another solution could be the use of constants or an enum so in your code it says reseller but your database still uses an int.

    Cheers

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search