Barry D.
Barry D.

Reputation: 547

Laravel Many-to-many relationship using pivot table

I'm creating an application wherein users can be assigned to multiple organisations, and organisations can have many users - many-to-many relationships.

I want to be able to do something like this: $user->organisations()->get() as well as $organisation->users()->get()

Note

The user_orgs table has an org_id field, and a user_id field.

Eloquent assumes and expects organisation_user - but that is not what I have named my table, nor do I want to rename.

I set up the following

App/Organisation.php

public function users(){
    return $this->belongsToMany("App\User");
}

and on user:

App/User.php

public function organisations(){
    return $this->belongsToMany("App\Organisation");
}

And then I test this:

Route::get('/test-route', function(){
    $u = App\User::first();
    return $u->organisations()->get();
});

and get the following error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.organisation_user' doesn't exist (SQL: select organisations.*, organisation_user.user_id as pivot_user_id, organisation_user.organisation_id as pivot_organisation_id from organisations inner join organisation_user on organisations.id = organisation_user.organisation_id where organisation_user.user_id = 1)

The two questions in my mind are, one; how do I specify to Eloquent, to use user_orgs instead of assuming organisation_user, the same way I can override the tableName or primaryKey on a model? Two: how can I specify the foreignKey column, such that it uses user_orgs.org_id and not user_orgs.organisation_id?

But please do suggest alternatives.

Thanks all, in advance.

Upvotes: 1

Views: 76

Answers (1)

atymic
atymic

Reputation: 3128

You can set the name of the pivot table by passing it as the second argument to the belongsToMany() relationship, like below:

public function users(){
    return $this->belongsToMany("App\User", "user_orgs");
}

public function organisations(){
    return $this->belongsToMany("App\Organisation", "user_orgs");
}

Documentation: https://laravel.com/docs/5.8/eloquent-relationships#many-to-many

As mentioned previously, to determine the table name of the relationship's joining table, Eloquent will join the two related model names in alphabetical order. However, you are free to override this convention. You may do so by passing a second argument to the belongsToMany method.

Upvotes: 2

Related Questions