gpt4 book ai didi

laravel - (Laravel) 通过数据透视表的多态关系

转载 作者:行者123 更新时间:2023-12-04 11:41:48 25 4
gpt4 key购买 nike

比方说,我有一个 Event 模型,它通过多态关系和一个数据透视表(EventParticipant)有更多的各种模型(Player、Coach、Admin)的参与者,其中还包含一个 bool 列 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'
];
}

在事件的情况下如何修改, 参与者()可以是 Player、Coach 或 Admin 模型? (也许与 MorphPivot 类有关,但我无法想象如何。)

(而不是 player_id(在 TrainingPlayer 类中)指的是 Player 模型的 id,有两列 rolerollable_id(在 EventParticipant 类中),它们指的是 Player、Coach、或管理模型,分别)

class Event extends Model
{
/**
* Event has more participants (players, coaches, or admins).
*/
public function participants() {
//
}
}

class EventParticipant extends MorphPivot
{
//
}

任何帮助将不胜感激。 :) 谢谢

最佳答案

我一直在寻找类似的东西并想出了一个解决方案。根据 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
}

关于laravel - (Laravel) 通过数据透视表的多态关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52579682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com