Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent - Attach vs Sync

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!

like image 643
Kousha Avatar asked May 31 '14 09:05

Kousha


People also ask

What is difference between attach and sync in Laravel?

The attach function only adds records to the Pivot table. The sync function replaces the current records with the new records. This is very useful for updating a model.

What is detach Laravel?

The detach method Similarly, if you want to remove a certain entity relationship from the pivot table, you can use detach method. For instance, if you want to remove a certain author from a book you can do like so. $book->authors()->detach($authorId); Or you can pass multiple IDs as an array.

What is hasMany in Laravel?

hasMany relationship in laravel is used to create the relation between two tables. hasMany means create the relation one to Many. For example if a article have comments and we wanted to get all comments of the article then we can use hasMany relationship .

How do I save a one to many relationship in Laravel?

You just need to pass the array of options with id, if id is present already in the database then it will update, if id is blank it will add a new record, If Id was there but not in your new array, then that record will get deleted.


1 Answers

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  
like image 184
Anam Avatar answered Oct 24 '22 21:10

Anam