Reputation: 6369
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.
Upvotes: 0
Views: 83
Reputation: 219930
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');
Upvotes: 3