Laravel 多态的 hasMany 关系
Laravel polymorphic hasMany relationship
根据Laravel的文档,模型多态性定义如下:
Polymorphic relations allow a model to belong to more than one other model on a single association
听起来它是为 belongsTo
而不是 hasMany
面设计的。这是我想要实现的场景:
在我的系统中,有很多项目类型,每个项目类型都会有自己的发票字段布局。假设我们有一个 Project
模型,它有一个 type
字段,其值可以是 contract
或 part-time
。我们还有另外两个名为 ContractInvoice
和 PartTimeInvoice
的表来定义它们各自的字段布局,这两个发票表都有一个 project_id
引用项目记录。我想要做的是我想要一个通用接口来检索给定项目的所有发票,例如 $project->invoices
.
当前解
我不知道如何通过多态性实现这一点。所以我目前正在做的事情有点傻,在 Project
模型 class:
上的 invoice()
方法中使用 switch
语句
switch ($this->type) {
case 'contract':
$model = 'App\ContractInvoice';
break;
case 'part-time':
$model = 'App\PartTimeInvoice';
break;
}
return $this->hasMany($model);
我觉得一定有更好的方法来做到这一点。有人可以解释一下吗?
我看不出多态关系在这种情况下会有什么好处。如果您有不同的项目类型模型和单个发票 table,那么发票可以变形为项目。但是正如您所描述的那样,switch 语句听起来就足够了。您可以使用 when
条件语句实现相同的方法,例如:
public function invoices()
{
return $this->when($this->type === 'contract', function () {
return $this->hasMany(ContractInvoice::class);
})->when($this->type === 'part-time', function () {
return $this->hasMany(PartTimeInvoice::class);
});
}
Project
模型上的 type
属性和单独的发票 table 定义了它们之间的严格关系,这违背了多态性的思想。将 likes
考虑为 comments
和 posts
。
根据Laravel的文档,模型多态性定义如下:
Polymorphic relations allow a model to belong to more than one other model on a single association
听起来它是为 belongsTo
而不是 hasMany
面设计的。这是我想要实现的场景:
在我的系统中,有很多项目类型,每个项目类型都会有自己的发票字段布局。假设我们有一个 Project
模型,它有一个 type
字段,其值可以是 contract
或 part-time
。我们还有另外两个名为 ContractInvoice
和 PartTimeInvoice
的表来定义它们各自的字段布局,这两个发票表都有一个 project_id
引用项目记录。我想要做的是我想要一个通用接口来检索给定项目的所有发票,例如 $project->invoices
.
当前解
我不知道如何通过多态性实现这一点。所以我目前正在做的事情有点傻,在 Project
模型 class:
invoice()
方法中使用 switch
语句
switch ($this->type) {
case 'contract':
$model = 'App\ContractInvoice';
break;
case 'part-time':
$model = 'App\PartTimeInvoice';
break;
}
return $this->hasMany($model);
我觉得一定有更好的方法来做到这一点。有人可以解释一下吗?
我看不出多态关系在这种情况下会有什么好处。如果您有不同的项目类型模型和单个发票 table,那么发票可以变形为项目。但是正如您所描述的那样,switch 语句听起来就足够了。您可以使用 when
条件语句实现相同的方法,例如:
public function invoices()
{
return $this->when($this->type === 'contract', function () {
return $this->hasMany(ContractInvoice::class);
})->when($this->type === 'part-time', function () {
return $this->hasMany(PartTimeInvoice::class);
});
}
Project
模型上的 type
属性和单独的发票 table 定义了它们之间的严格关系,这违背了多态性的思想。将 likes
考虑为 comments
和 posts
。