我有一个只有其他两个表的ID的表,我想要一个n:m关系,但是现在每次我保存一个记录,如果已经使用了两个id中的一个,它会删除前一个。
我的迁移:
Schema::create('show_user', function(Blueprint $table) {
$table->integer('show_id')->unsigned()->index();
$table->foreign('show_id')->references('id')->on('shows');
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users');
});
我的模特:
USER
public function shows()
{
return $this->belongsToMany('App\Show');
}
显示
public function users()
{
return $this->belongsToMany('App\User');
}
这就是我保存到数据透视表的方式:
User::find($userid)->shows()->sync([$showid, $userid])
当我为用户1(我)执行此操作时,在节目5中,它保存1和5,当我再次尝试显示12上的同一用户时,它保存1和12并删除之前的1和5记录。如果我通过phpMyAdmin手动插入,我可以添加多个记录,但不能使用同步。我也试过这个,结果相同:
User::find($userid)->shows()->sync([$showid])
答案 0 :(得分:2)
您没有正确使用sync()
。 sync()
用于从Shows
添加并删除 User
,并且需要Show
ids
的数组。因此,如果您致电sync([1,5])
,则会将Shows
{1}}的{{1}}添加到ids
并删除之前与该User
关联的所有其他Shows
1}}。
您可以阅读inserting related-models in Laravel here,但您可能只需要了解以下三个示例:
如果User
与User
3,4和8有关系,并且您希望确保Shows
仅与User
4和5有关系,那么您会这样做:
Shows
如果User::find($userid)->shows()->sync([4,5]); // Removes 3 and 8; Adds 5
已经与User
4建立了关系,并且您想添加Show
5,那么您会这样做:
Show
如果User::find($userid)->shows()->attach(5); // Adds 5
与User
3,4,5和8有关系,并且您想删除3和8,则可以执行此操作:
Shows
在每个示例之后,User::find($userid)->shows()->detach([3,8]); // Removes 3 and 8
只会与User
4和5建立关系。
答案 1 :(得分:0)
如果不起作用同步或同步保存两条记录。
此代码有效
$product->attributes()->sync([
1 => ['product_id' => $product],
1 => ['provider_id' => $provider]
]);