Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
377 views
Welcome To Ask or Share your Answers For Others

1 Answer

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, the sync() method is used to attach related models. However, the main differences are:

  • sync() accepts an array of IDs to place on the pivot table
  • Secondly, most important, the sync method will delete the data from the pivot table if the model does not exist in the array, and insert only the 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...