繁体   English   中英

Laravel 8 - 如何从 3 个表建立关系

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM