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?
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:
From the laravel docs: Laravel 5.3 eloquent many-to-many relationships
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.