我有 Playlist
和 Track
多对多关系与附加 order
field :
Schema::create('playlist_track', function (Blueprint $table) {
$table->integer('playlist_id')->unsigned();
$table->integer('track_id')->unsigned();
$table->integer('order')->unsigned();
$table->primary(['playlist_id', 'order']);
});
用户可以从播放列表中删除轨道并更改顺序。所以这个
sync
方法是我需要的: foreach ( $tracks as $key => $track ){
$_tracks[ $track ] = [ 'order' => $key ];
}
$playlist->tracks()->sync( $_tracks );
但是在尝试更改轨道顺序时出现错误:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '3-0' for key 'PRIMARY' (SQL: update `playlist_track` set `order` = 0 where `playlist_id` = 3 and `track_id` = 1)
那是因为我在使用复合主键,我猜......但我不知道如何使它工作
UPD
这是 dd( $_tracks )
array:2 [
1 => array:1 [
"order" => 0
]
3 => array:1 [
"order" => 1
]
]
最佳答案
由于它是一个数据透视表,您不能将外键定义为主键,因此删除它:
$table->primary(['playlist_id', 'order'])
数据透视表可以具有非唯一性
playlist_id
值,但带有 ->primary()
你正在创建一个约束。
关于Laravel 5.4 同步()上的 key 'PRIMARY' 的重复条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45241431/