What is the difference between syncWithoutDetaching and attach 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.
whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.
BelongsTo is a inverse of HasOne. We can define the inverse of a hasOne relationship using the belongsTo method. Take simple example with User and Phone models. I'm giving hasOne relation from User to Phone. class User extends Model { /** * Get the phone record associated with the user.
sync() method accepts an array of IDs to place on the pivot table. If the models does not exist in array the sync method will delete models from table and insert new items to the pivot table.
Laravel comes with handy little helper methods called attach, detach and sync in order to add certain amount of convenience for Many To Many relationships. Let’s review them one by one.
Laravel comes with handy little helper methods called attach, detach and sync in order to add certain amount of convenience for Many To Many relationships. Let’s review them one by one. The attach method. This specific helper method can be used to attach a certain entity record to the other entity record in the pivot table.
Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database. When using Eloquent, each database table has a corresponding "Model" that is used to interact with that table.
sync (): It is similar to attach (). The main difference between sync () and attach () is: 1) Sync method accepts an array of IDs to place on the pivot table. 2) 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.
Let's assume that you have auto-increment primary key id
in your pivot table, you will notice:
attach()
will add the new records to the pivot table, and pre-existed relations will get fresh ids.sync()
will remove all existed relations and set only provided in current request, with fresh ids too.syncWithoutDetaching()
will remove all existed relations except provided in current process, then the pre-existed rows won't get new ids.Two things:
attach()
will always add a new record to the pivot table, whereas syncWithoutDetaching()
will only add a new record if one does not exist.Let's say you have orders and items.
$order->items()->attach(1);
$order->items()->attach(1);
// $order->items()->count() === 2
$order2->items()->syncWithoutDetaching(1);
$order2->items()->syncWithoutDetaching(1);
// $order2->items()->count() === 1
attach()
returns null
, whereas syncWithoutDetaching()
returns an array showing what was attached/detached/updated.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With