dongshou9878 2014-04-10 02:50
浏览 32
已采纳

多对多的雄辩关系

I am trying to create a many to many relationship using Laravel 4.1 and Eloquent model. I have 3 tables - songs, artists and song_artist:

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

---- artists
        - id
        - name

---- song_artist
        - id
        - song_id
        - artist_id

Since each song can have multiple artists and each artist can have multiple songs, I assumed I would need to use the morphToMany() method instead of the hasMany() or hasManyThrough() methods.

How would I set up the relation so that I could access the artists related to a song by $song->artists(), as well as access the songs related to an aritst by using $artist->songs()?

I've already looked into other questions on SO such as this one, this one and this one.

Any help would be much appreciated.

  • 写回答

1条回答 默认 最新

  • doumu5662 2014-04-10 02:52
    关注

    Rename song_artist to artist_song, then use belongsToMany.

    If you don't want to rename your table, set it manually:

    // In Artist
    return $this->belongsToMany('Song', 'song_artist');
    
    // In Song
    return $this->belongsToMany('Artist', 'song_artist');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程