比方说,我有一个事件模型,该模型通过多态关系和数据透视表(EventParticipant)拥有更多的各种模型(Player,Coach,Admin)的参与者,该数据透视表还包含一个布尔列participate
。我想通过$ event->参与者获得参与者,参与者通过多态关系检索球员,教练和管理员的集合。
我在训练中使用标准的非多态关系创建了类似的东西,
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'
];
}
在事件(参与者()可以是玩家,教练或管理员模型)的情况下如何修改?(也许是MorphPivot类的东西,但我无法想象如何。 )
(而不是引用Player模型的player_id
的{{1}}(在TrainingPlayer类中),有两列id
和role
(在EventParticipant类中)分别指的是Player,Coach或Admin模型的rollable_id
id
任何帮助将不胜感激。 :) Thx
答案 0 :(得分:1)
我一直在寻找类似的东西,并提出了解决方案。根据乔纳斯(Jonas)的评论,在1个相关的集合中不能有不同的模型,但是可以使用1个数据透视表为每个模型使用1个模型。
您现在可以使用\App\Team::find(1)->with(['managers', 'users'])->get();
Schema::create('associations', function (Blueprint $table) {
$table->id();
$table->string('association_type');
$table->integer('association_id');
$table->integer('team_id');
$table->integer('meta')->nullable();
$table->timestamps();
});
Schema::create('managers', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
Schema::create('teams', function (Blueprint $table) {
$table->id();
$table->timestamps();
});
class Manager extends Model
{
public function teams()
{
return $this->belongsToMany('\App\Team', 'associations')->using('App\Association');
}
}
class Team extends Model
{
public function managers()
{
return $this->morphedByMany('App\Manager', 'association')->using('App\Association');
}
public function users()
{
return $this->morphedByMany('App\User', 'association')->using('App\Association');
}
}
class User extends Authenticatable
{
public function teams()
{
return $this->belongsToMany('\App\Team', 'associations')->using('App\Association');
}
}
// App/Association
use Illuminate\Database\Eloquent\Relations\MorphPivot;
class Association extends MorphPivot
{
protected $table = 'associations'; // not sure if this is needed
}