【问题标题】:Laravel: Which relationship to use?Laravel:使用哪种关系?
【发布时间】:2017-09-07 23:09:10
【问题描述】:

我有以下场景:

我正在建立一个网站,艺术家可以在其中展示他们在城市中最喜欢的景点。 所以: 有一些Cities 和一些Artists。一个城市hasManySpotsArtistsSpots 也通过 belongsToMany 关联在一起,因为一个 Spot 可能被多个 Artists 推荐。

我现在想在 City 中定义一个关系,它为我提供了在该城市中具有特色的所有艺术家(所以基本上寻找与该城市的某个地点相关的艺术家)

是否有我可以使用的关系类型? 我试过hasManyThrough,但那是在Artist 中查找spot_id,这显然不存在,因为ArtistSpot 是多对多的。

【问题讨论】:

    标签: php laravel orm eloquent


    【解决方案1】:

    当您有多对多关系时,您需要对两个表进行规范化,创建新表来存储 spot_id 和 Artist_id。我认为在 laravel 中已经处理好了。此链接可能会有所帮助

    https://laravel.com/docs/5.5/eloquent-relationships#many-to-many https://www.captechconsulting.com/blogs/resolve-your-many-to-manys-for-accurate-requirements

    【讨论】:

      【解决方案2】:

      虽然这是多对多的关系,所以你必须使用belongsToMany 例如:

      在城市模型中:

      class City extends Model{
            public function artists(){
              return $this->belongsToMany('App\Artist')
            }
      }
      

      在艺术家模型中:

      class Artist extends Model{
            public function city(){
              return $this->belongsToMany('App\City')
            }
      }
      

      【讨论】:

      • 这在我的情况下不起作用,因为艺术家没有直接连接到城市。它们是通过 Spot 模型(一个 Spot 属于一个城市;Spot 和 Artist 通过 manyToMany 关系关联)
      • 因此,在城市模型中,您可以提供与点的关系,而在点模型中,您可以提供与艺术家的关系,因此无论何时您想使用,都可以将其用作点。艺术家
      猜你喜欢
      • 2015-03-22
      • 2023-01-31
      • 2016-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 2018-08-28
      • 1970-01-01
      相关资源
      最近更新 更多