在Laravel Eloquent中,如何通过二次表来定义关系?(始终返回0个关系)



我觉得这应该有效。我有一份产品和类别(类型(的清单。

表格:

Products
- id
- name
- etc
Types
- id
- name
- etc
ProductTypes
- product_id
- type_id

现在,我觉得在Laravel的Type模型中,我应该能够定义这种关系:

public function products()
{
return $this->hasManyThrough(Product::class, ProductType::class, 'type_id', 'id');
}

我尝试过在附加参数中使用次要id的其他变体,但没有成功,总是一个空列表。ProductTypes是否是一个数据透视表,因此应该以不同的方式处理?

编辑:奇怪的是,对于最后两个参数($localKey = null, $secondLocalKey = null(,即使我输入了完整的垃圾,也不会抛出错误,但这两个参数$firstKey = null, $secondKey = null必须是正确的(。

您使用了错误的关系。根据您的数据库结构,一个产品可以属于多种类型。因此,它应该是BelongsToMany而不是HasManyThrough

通过传递ProductTypes的表名作为第二个参数,您可以使用以下方法实现您想要的内容:

public function products()
{
return $this->belongsToMany(Product::class, 'product_types');
}

如果你的ProductType模型扩展了IlluminateDatabaseEloquentRelationsPivot,你可以做:

public function products()
{
return $this->belongsToMany(Product::class, 'product_types')
->using(ProductType::class);
}

有关多对多关系的更多信息:https://laravel.com/docs/6.x/eloquent-relationships#many-到许多

最新更新