简体   繁体   中英

Many to Many Eloquent Relation

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.

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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