如何与Eloquent建立多态关系
How to establish polymorphic relations with Eloquent
使用 Laravel 和 Eloquent。我有一个看起来像这样的数据库:
dance_performers.dance_perfomer_type
字段包含 '\App\Dancer'
、'\App\Couple'
或 '\App\Formation'
等值。
您将如何继续将 dance_performers.dance_perfomer_id
连接到不同的模型?我不确定我应该如何在不同的模型中编写这些关系。
我是否应该创建一个 \App\Performer
模型,然后将其定向到前面提到的三个模型之一?
使用多态关系:
class Dance extends Model {
public function couples() {
return $this->morphedByMany('\App\Couple', 'dance_performer');
}
}
class Couple extends Model
{
public function dances() {
return $this->morphToMany('App\Dance', 'dance_performer');
}
}
目前,$dances = \App\Dance::with('couples')->get();
只有 returns 个空关系。
我将不胜感激。
根据您的代码,一切都是正确的。我猜你在数据库中没有正确的数据。
添加如下数据并检查。
dances
id - 1, name - 'Dance A'
id - 2,名称 - 'Dance B'
couples
id - 1,名称 - 'Couple A'
id - 2, name - 'Couple B'
dance_performers
id - 1, dance_id - 1, dance_performer_type - '\App\Couple', dance_performer_id - 1
id - 2, dance_id - 2, dance_performer_type - '\App\Couple', dance_performer_id - 2
解决了。 type
字段应该是 App\ModelName
而不是 \App\ModelName
.
使用 Laravel 和 Eloquent。我有一个看起来像这样的数据库:
dance_performers.dance_perfomer_type
字段包含 '\App\Dancer'
、'\App\Couple'
或 '\App\Formation'
等值。
您将如何继续将 dance_performers.dance_perfomer_id
连接到不同的模型?我不确定我应该如何在不同的模型中编写这些关系。
我是否应该创建一个 \App\Performer
模型,然后将其定向到前面提到的三个模型之一?
使用多态关系:
class Dance extends Model {
public function couples() {
return $this->morphedByMany('\App\Couple', 'dance_performer');
}
}
class Couple extends Model
{
public function dances() {
return $this->morphToMany('App\Dance', 'dance_performer');
}
}
目前,$dances = \App\Dance::with('couples')->get();
只有 returns 个空关系。
我将不胜感激。
根据您的代码,一切都是正确的。我猜你在数据库中没有正确的数据。 添加如下数据并检查。
dances
id - 1, name - 'Dance A'
id - 2,名称 - 'Dance B'
couples
id - 1,名称 - 'Couple A'
id - 2, name - 'Couple B'
dance_performers
id - 1, dance_id - 1, dance_performer_type - '\App\Couple', dance_performer_id - 1
id - 2, dance_id - 2, dance_performer_type - '\App\Couple', dance_performer_id - 2
解决了。 type
字段应该是 App\ModelName
而不是 \App\ModelName
.