我正在开发一个 Fantasy 体育应用程序。我正在使用的模型是 FantasyPlayer、PlayerGame、TeamGame
FantasyPlayer 可以有很多 PlayerGame 也可以有很多 TeamGame
public function PlayerGame()
{
return $this->hasMany('App\Models\PlayerGame','player_id','player_id');
}
public function TeamGame()
{
return $this->hasMany('App\Models\FantasyData\TeamGame','team','fantasy_player_key');
}
当我加载数据时,我目前使用急切加载:
FantasyPlayer::with(['PlayerGame', 'TeamGame'])->take(1)->get();
加载两个关系然后加载哪些关系变得乏味。理想情况下,我想让模型处理这个逻辑。所以我可以做这样的事情:
FantasyPlayer::with(['FantasyGame'])->take(1)->get();
然后我的 FantasyGame 范围将包含我需要基于位置的 FantasyPlayer 值的 PlayerGame 或 TeamGame 记录。像这样的东西是我想要的......但它对我不起作用:
public function scopeFantasyGame($query)
{
if($this->position == "DEF"){
return $this->TeamGame();
}
else{
return $this->PlayerGame();
}
}
有谁知道我可以使用预先加载并让 FantasyGame 根据 FantasyPlayer 位置属性返回正确关系的方法?:
FantasyPlayer::with(['FantasyGame'])->take(1)->get();