【问题标题】:Many to Many Eloquent Relation多对多雄辩的关系
【发布时间】:2014-05-23 13:18:11
【问题描述】:

我正在尝试使用 Laravel 4.1 和 Eloquent 模型创建多对多关系。我有 3 张表 - 歌曲、艺术家和 song_artist:

---- songs 
        -- id
        -- title
        -- genre

---- artists
        - id
        - name

---- song_artist
        - id
        - song_id
        - artist_id

由于每首歌曲可以有多个艺术家,每个艺术家可以有多个歌曲,我假设我需要使用morphToMany() 方法而不是hasMany()hasManyThrough() 方法。

如何设置关系,以便我可以访问与$song->artists() 的歌曲相关的艺术家,以及使用$artist->songs() 访问与某位艺术家相关的歌曲?

我已经研究过关于 SO 的其他问题,例如 this onethis onethis one

任何帮助将不胜感激。

【问题讨论】:

    标签: php laravel polymorphism many-to-many eloquent


    【解决方案1】:

    song_artist 重命名为artist_song,然后使用belongsToMany

    如果您不想重命名表格,请手动设置:

    // In Artist
    return $this->belongsToMany('Song', 'song_artist');
    
    // In Song
    return $this->belongsToMany('Artist', 'song_artist');
    

    【讨论】:

      猜你喜欢
      • 2016-11-03
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 2012-10-08
      • 2018-03-28
      • 2018-10-27
      • 2017-10-16
      • 1970-01-01
      相关资源
      最近更新 更多