简体   繁体   English

如何更新 laravel 中的 pivot 表?

[英]How to update pivot table in laravel?

My header question looks so broad.我的 header 问题看起来很广泛。 Let me just describe it below.让我在下面简单描述一下。

I have 3 tables the posts , tags , and post_tags .我有 3 张表,分别是poststagspost_tags I have use syncWithoutDetaching and so far its working fine.我使用syncWithoutDetaching ,到目前为止它工作正常。 My only issue is when I do updating, it does not do the exact thing I expected.我唯一的问题是,当我进行更新时,它并没有达到我的预期。

Lets say I have already existing data(below picture).假设我已经有数据(下图)。

在此处输入图像描述

And I want to send again another data我想再次发送另一个数据

"tags":[1,3]

I expect using syncWithoutDetaching it would output these data below我希望使用syncWithoutDetaching它会 output 这些数据如下

在此处输入图像描述

But it returns it results into three like below但它会将结果返回为三个,如下所示

在此处输入图像描述


Someone knows how to achieve this expectation, I think syncWithoutDetaching is not the perfect fit for this.有人知道如何实现这个期望,我认为syncWithoutDetaching并不适合这个。

the behavior that you are after is Sync with detaching.您所追求的行为是 Sync with detaching。 So use sync()所以使用sync()

Basicly, when you use sync , giving it "tag":[1,4] will remove existing entries and add the new ones, so only tag id 1 and 4 will still be there基本上,当您使用sync时,给它"tag":[1,4]将删除现有条目并添加新条目,因此只有标签 id 1 和 4 仍然存在

Using syncWithoutDetaching , giving it "tag":[1,4] will add the tag id 1 and 4 on top of what is already in there (without risk of duplication)使用syncWithoutDetaching ,给它"tag":[1,4]会将标签 id 1 和 4 添加到已经存在的内容之上(没有重复的风险)

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

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