I'm working on a Fantasy sports app. The models I am working with are FantasyPlayer, PlayerGame, TeamGame
FantasyPlayer can have many PlayerGame and can have many 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');
}
When I load the data I use eager loading currently:
FantasyPlayer::with(['PlayerGame', 'TeamGame'])->take(1)->get();
It is becoming tedious to load both relationships and then which are loaded. Ideally, I want to have the model handle this logic for. So I would be able to do something like this:
FantasyPlayer::with(['FantasyGame'])->take(1)->get();
Then my FantasyGame scope would contain either the PlayerGame or the TeamGame record I need based on an a FantasyPlayer value for the position. Something like this is what I want... but it doesn't work for me:
public function scopeFantasyGame($query)
{
if($this->position == "DEF"){
return $this->TeamGame();
}
else{
return $this->PlayerGame();
}
}
Does anyone know way I could use eager loading and have the FantasyGame return the correct relationship based on a FantasyPlayer position attribute?:
FantasyPlayer::with(['FantasyGame'])->take(1)->get();