比方说,我有一个 Event 模型,它通过多态关系和一个数据透视表(EventParticipant)有更多的各种模型(Player、Coach、Admin)的参与者,其中还包含一个布尔列participate。我想通过 $event->participants 获取参与者,它通过多态关系检索球员、教练和管理员的集合。
我在训练中使用标准非多态关系创建了类似的东西,如下所示:
class Training extends Model
{
/**
* Training has more players.
*/
public function players() {
return $this->belongsToMany('App\Player', 'training_player')
->using('App\TrainingPlayer')
->withPivot('participate');
}
}
class TrainingPlayer extends Pivot
{
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'participate' => 'boolean'
];
}
Run Code Online (Sandbox Code Playgroud)
在事件的情况下如何修改,参与者()可以是玩家、教练或管理员模型?(也许与 MorphPivot 类有关,但我无法想象如何。)
(而不是player_id(在 TrainingPlayer 类中)指id的是 Player 模型,有两列role和rollable_id(在 EventParticipant …