Does Eloquent relation sync also remove?

让人想犯罪 __ 提交于 2019-12-10 03:00:44

问题


When updating a model and I sync a relationship, if I don't pass in all the ids that already exist, will that relationship be removed?


回答1:


You decide: sync has 2nd parameter that defaults to true and is responsible for detaching:

$model->relationship()->sync([1,2,3]);

$model->relationship()->sync([4,5,6]); // attached [4,5,6], detached [1,2,3]
$model->relationship()->getRelatedIds(); // [4,5,6]

// but:
$model->relationship()->sync([4,5,6], false); // attached [4,5,6], detached []
$model->relationship()->getRelatedIds(); // [1,2,3,4,5,6]



回答2:


The answer is Yes it does. I could not find any documentation that in fact stated that.

lets say you have 2 tables: "authors" and "books", with a pivot table "book_authors".

when creating a new author:

$author_id =2;
$author->books()->sync(array(1,4,5,15));

Now you have a 4 entries in that pivot table "book_authors":

author_id  book_id
2          1
2          4
2          5
2          15

Now update:

$author_id =2;
$author->books()->sync(array(1,15));

now "book_authors" is:

author_id  book_id
    2          1
    2          15


来源:https://stackoverflow.com/questions/24208073/does-eloquent-relation-sync-also-remove

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!