【发布时间】:2019-04-29 21:47:50
【问题描述】:
我正在开发一款 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();
【问题讨论】:
-
你没有提供足够的信息来确定,但这听起来可能是使用 Laravel polymorphic relationships 的好候选人。
-
如果只返回 1 个结果,是否需要预先加载?
标签: php laravel eloquent eloquent-relationship