[英]Laravel 8 - How to relationship from 3 tables
我有 3 张桌子:
structurals
id
name
indicators
id
name
groupings
id
structural_id
indicator_id
结果:
#structural name
indicator name
indicator name
#structuralname
indicator name
我使用了方法 hasMany & hasManyThrough 但是错误。
在这种情况下,一个indicator
可能属于一个或多个structural
指标。 而一个structural
可以有一个或多个indicators
。
这描述的是many-to-many
关系,其中groupings
只是一个 pivot 表。 所以你应该改用belongsToMany
:
class Indicator extends Model
{
public function structurals()
{
return $this->belongsToMany(Structural::class, 'groupings');
}
}
class Structural extends Model
{
public function indicators()
{
return $this->belongsToMany(Indicator::class, 'groupings');
}
}
文档: https://laravel.com/docs/eloquent-relationships#many-to-many
您还可以从groupings
表中删除id
列,因为它是不必要的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.