Reputation: 246
I have the following database schema:
The following is intended for this scheme:
1 user can have several teams and a team can have up to two users (I assumed it is a many-to-many relationship and then I validate whether or not a team has only two users)
1 team can have multiple games and a game only has a home_team (team) and an away_team (team) here I assumed it will have two 1 to many relationships (1 team has multiple games and a game only has an away_team and a home_team).
My question is how should I make their relationships in the models, for example, to get through a user all his games, both away_team and home_team.
I try this:
public function awayTeam()
{
return $this->belongsTo(Team::class, 'uuid');
}
public function homeTeam()
{
return $this->belongsTo(Team::class, 'uuid');
}
Team Model
public function homeGames()
{
return $this->hasMany(Game::class, 'uuid', 'home_team_uuid');
}
public function awayGames()
{
return $this->hasMany(Game::class, 'uuid', 'away_team_uuid');
}
User Model
public function teams()
{
return $this->belongsToMany(Team::class);
}
Upvotes: 0
Views: 873
Reputation: 246
O find the problem:
in Team model i need declare 'foreign_key' and 'local_key' like that, because i dont use convencional fields
public function homeGames()
{
return $this->hasMany(Game::class, 'home_team_uuid', 'uuid');
}
public function awayGames()
{
return $this->hasMany(Game::class, 'away_team_uuid', 'uuid');
}
In Game model i change for that, for same reason:
public function awayTeam()
{
return $this->belongsTo(Team::class, 'away_team_uuid', 'uuid');
}
public function homeTeam()
{
return $this->belongsTo(Team::class, 'home_team_uuid', 'uuid');
}
and now i can have relation response.
Upvotes: 0