Reputation: 21
I have 2 tables users and teams, that make a relation table user_team.
The user_team table have cod_user and cod_equipe columns and make references to column cod on users, and cod on teams.
This relation returns NULL
User model
public function user_team(){
//belongs to -> pertence a
return $this->belongsToMany('App\User','user_team','cod_user','cod_equipe');
}
Team model
public function team_user(){
//belongs to -> pertence a
return $this->belongsToMany('App\Team','user_team','cod_equipe','cod_user');
}
I think its because Eloquent try to JOIN cod_user with ID on users, but the reference is on cod column.
How can i change this?
Upvotes: 2
Views: 6184
Reputation: 166
Could you clarify what your database schema looks like regarding these tables? In order to make the relations work when defining them explicitly, you need to specify the foreign key from the model in question, followed by the foreign key of the table you want to join. I am confused by the use of 'cod' here as the foreign key mentioned in both users and teams tables. Is the foreign key reference from the users table a field called 'cod', and the same for teams?
If so, you would need to specify that as the foreign key on your users model, and assuming that 'cod_user' is the key in user_team, it would look like this in the User model:
public function userTeam(){
return $this->belongsToMany('App\User','user_team','cod','cod_user');
}
From the laravel docs: Laravel 5.3 eloquent many-to-many relationships
In addition to customizing the name of the joining table, you may also customize the column names of the keys on the table by passing additional arguments to the belongsToMany method. The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
Additionally, if the primary key on the users or teams table is not named 'id', then you will have to override the convention by defining the variable $primaryKey in your User and Team models.
Upvotes: 4