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!
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
attach():
Example:
sync()
Similar to the
attach()
method.sync()
also use to attach related models. However main difference is:Example:
user_role
The above operation will delete:
And insert
role_id 3
to the table.user_role table
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].