Reputation: 547
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()
users
table...organisations
table...user_orgs
pivot/mapping/etc. tableThe 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
public function users(){
return $this->belongsToMany("App\User");
}
and on user:
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
aspivot_user_id
,organisation_user
.organisation_id
aspivot_organisation_id
fromorganisations
inner joinorganisation_user
onorganisations
.id
=organisation_user
.organisation_id
whereorganisation_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
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