我是laravel的新手,以前从未为实体的播放列表类型建模,所以我正在寻找最佳实践和指导。
我有两种型号的歌曲和播放列表。
播放列表中有许多歌曲。我希望用户能够填写一个表格来创建/编辑播放列表,并选择他们喜欢的歌曲。
最好的方法是什么?有没有办法将一组id存储为歌曲表的外键?还是应该总是将多行写入映射表?
laravel或雄辩家有办法为这种模型在CRUD中提供帮助吗?什么是最佳实践?
playlist_song
表并存储song
和playlist
之间的所有关系。
可以使用attach
、detach
和sync
方法来控制外部关系。为了更容易理解,我举了一个例子:
class Song extends 'Eloquent {
public function playlists() {
return $this->belongsToMany('Model'Playlist', 'playlist_song');
}
}
class Playlist extends 'Eloquent {
public function songs() {
return $this->belongsToMany('Model'Songs', 'playlist_song');
}
}
在你的控制器中,你可以使用这样的东西来同步播放列表中包含的所有歌曲:
$playlist->songs()->sync(array(1, 2, 3)); // The numbers are the ids
有关Laravel Eloquent的完整文档,请查看http://laravel.com/docs/4.2/eloquent