我有足球游戏,其 home_team 和 away_team
我对Game.php的关系如下:
public function hometeam()
{
return $this->hasOne(Team::class, 'id', 'home_team_id');
}
public function awayteam()
{
return $this->hasOne(Team::class, 'id', 'away_team_id');
}
现在,我想查看每个团队,了解它所属的游戏。
我在Team.php中尝试了以下内容,但它返回 null
public function homeGames()
{
return $this->belongsTo('App\Models\Game', 'home_team_id', 'id');
}
public function awayGames()
{
return $this->belongsTo('App\Models\Game', 'away_team_id', 'id');
}
对于away_team_id offcourse也一样。
我错过了什么吗?
谢谢!
答案 0 :(得分:1)
你的游戏桌不应该有2个外键球队表,一个用于主队,一个用于客队吗? (一对多的关系)。
这样,您可以执行类似$team->homeGames
和$team->awayGames
的操作,您将获得针对特定团队的所有主场比赛和客场比赛。
此外,Team模型应该有2个return $this->hasMany(Game::class);
方法,而Game模型应该有2 x return $this->belongsTo(Team::class);
更新:
Team.php模型
class Team extends Model
{
public function homeGames()
{
return $this->hasMany(Game::class, 'id', 'home_team_id');
}
public function awayGames()
{
return $this->hasMany(Game::class, 'id', 'away_team_id');
}
}
Game.php模型
class Game extends Model
{
public function homeTeam()
{
return $this->belongsTo(Team::class, 'home_team_id', 'id');
}
public function awayTeam()
{
return $this->belongsTo(Team::class, 'away_team_id', 'id');
}
}