繁体   English   中英

Laravel Eloquent Model 在多对多关系中无法与 pivoty 数据同步

[英]Laravel Eloquent Model can't sync with pivot data in Many-to-Many relationship

我想同步数据而不是将数据附加到特定关系。

Pivot 关系用户型号代码

public function carts(){
        return $this->belongsToMany(Product::class,'user_carts')->withPivot('quantity');
    }

附件代码是

User::find(1)->carts()->attach($s,["quantity"=>1]);

同步码是

User::find(1)->carts()->sync($s,["quantity"=>1]);

当我尝试编译同步时,那些匹配 user_id = 1 的 pivot 关系在其各自的数量列中没有“1”。

如果我想在不使用附加的情况下实现同步 function,我该怎么做,因为 attach() 会在我的数据库中创建多个冗余数据。

您必须在sync方法中传递键值。 假设$s是要同步的 id(键):

User::find(1)->carts()->sync([$s => ["quantity"=>1]]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM