Search code examples
phplaraveleloquentfluent

Relation 3 tables Laravel


I have 3 tables :

playlists

id | secret | [...]
1    xjdjd    
2    dzfze

playlists_songs

id | playlist_id | song_id | [...]
1    1             83
2    1             32

songs

id | name | [...]
22

I want fetch all songs of a playlist.

Right now my code looks like :

<?php

class Playlist extends Eloquent {

public function playlistSongs()
{
    return $this->hasMany('PlaylistSong');
}



<?php

class PlaylistSong extends Eloquent {


    public function playlist()
    {
        return $this->belongsTo('Playlist');
    }

}

Right now i can fetch all "playlist songs" of a playlist like this :

    // Check if the playlist exists
    $playlist = Playlist::where('secret', $secret)->firstOrFail();


    // We want fetch all songs of a playlist
    $playlistSongs = $playlist->playlistSongs()->get();

But i dunno how to fetch all songs name ...

Have a good day :)


Solution

  • What you're describing is a many-to-many relation. In Laravel, it is described like this:

    class Playlist extends Eloquent {
    
        public function songs()
        {
            return $this->belongsToMany('song', 'playlists_songs', 'playlist_id', 'song_id');
        }
    
    }
    

    Now, you can get all songs from playlist with:

    $playlist->songs