Laravel Eloquent - Attach vs Sync

允我心安 提交于 2019-11-26 11:58:46

问题


What is the difference between attach() and sync() in Laravel 4\'s Eloquent ORM? I\'ve tried to look around but couldn\'t find anything!


回答1:


attach():

  • Insert related models when working with many-to-many relations
  • No array parameter is expected

Example:

$user = User::find(1);

$user->roles()->attach(1);

sync()

Similar to the attach() method. sync() also use to attach related models. However main difference is:

  • Sync method accepts an array of IDs to place on the pivot table
  • Secondly, most important, The sync method will delete the models from table if model does not exist in array and insert new items to the pivot table.

Example:

user_role

id  user_id role_id
1    12       1
2    12       5
3    12       2
$user = User::find(12);
$user->roles()->sync(array(1, 2, 3));

The above operation will delete:

id  user_id role_id
2    12       5

And insert role_id 3 to the table.

user_role table

id  user_id role_id
1    12       1
3    12       2
4    12       3




回答2:


To make it even simpler:

The attach function only add records to the Pivot table.

The sync function replaces the current records with the new records. This is very useful for updating a model.

Example:

Assuming you have a created Post that has many Tags attached on it where the Tags ID's are [1,2,3].

And the user has the ability to update the Post and its Tags.

The user will send you the new Tags ID's [3,4,5].

If you use the sync function, the new Tags of the Post will be [3,4,5] only.

But if you use the attach function, the new Tags of the Post will be [1,2,3,4,5].



来源:https://stackoverflow.com/questions/23968415/laravel-eloquent-attach-vs-sync

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