【问题标题】:Relation 3 tables Laravel关系 3 表 Laravel
【发布时间】:2014-08-25 06:10:41
【问题描述】:

我有 3 张桌子:

播放列表

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

播放列表_歌曲

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

歌曲

id | name | [...]
22

我想获取播放列表中的所有歌曲。

现在我的代码看起来像:

<?php

class Playlist extends Eloquent {

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



<?php

class PlaylistSong extends Eloquent {


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

}

现在我可以像这样获取播放列表的所有“播放列表歌曲”:

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


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

但我不知道如何获取所有歌曲的名称...

祝你有美好的一天:)

【问题讨论】:

    标签: php laravel eloquent fluent


    【解决方案1】:

    您所描述的是many-to-many 关系。在 Laravel 中是这样描述的:

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

    现在,您可以通过以下方式从播放列表中获取所有歌曲:

    $playlist->songs
    

    【讨论】:

    • 哦,这很容易......谢谢老兄:)
    猜你喜欢
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    • 2017-07-09
    • 1970-01-01
    • 2023-03-12
    • 2019-05-17
    相关资源
    最近更新 更多