我有三个表playlist
,music
和数据透视表playlist_music
,我想在数据透视表playlist_music
中添加播放列表和音乐。我的音乐是music_ids : [1,2,3]
。我也必须将index
存储在数据透视表中,所以我的代码是:
public function create(array $attributes = [])
{
$playlist = parent::create($attributes);
if (isset($attributes['music_ids'])) {
$playlistMusic = $attributes['music_ids'];
$music = [];
foreach ($playlistMusic as $index => $music ) {
$tracks[$music['music_id']] = ['index' => $index];
$tracks[$music['music_id']] = $music;
}
$playlist->music()->sync($music);
}
return $playlist;
}
现在,只有数组中的最后一个值存储在字段music_id
中。如何将数组music_ids
中的所有单个值存储到数据透视表中的字段music_id
中。这是在belongsToMany关系中。请建议我。任何帮助将不胜感激。