Laravel Eloquent - Attach vs. SyncWithoutDetaching
Asked Answered
A

3

17

What is the difference between syncWithoutDetaching and attach in Laravel?

Administrator answered 30/5, 2020 at 14:53 Comment(0)
C
26

Let's assume that you have auto-increment primary key id in your pivot table, you will notice:

  1. attach() will add the new records to the pivot table, and pre-existed relations will get fresh ids.
  2. sync() will remove all existed relations and set only provided in current request, with fresh ids too.
  3. syncWithoutDetaching() will not remove all existing relations missing from the one provided in current process, then the pre-existed rows won't get new ids.
Crinoid answered 30/5, 2020 at 18:16 Comment(0)
C
19

Two things:

  1. 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
  1. attach() returns null, whereas syncWithoutDetaching() returns an array showing what was attached/detached/updated.
Compatriot answered 30/5, 2020 at 16:5 Comment(0)
C
4

attach() will add new records even if they already exist. sync() will remove records that don't exist in the sync(), leave untouched those that already do, and add the ones that don't. syncWithoutDetaching() is the same as sync() but doesn't remove anything.

So

1: Apple, 2: Banana, 3: Carrot

attach(['Apple', 'Date']) -> 1: Apple, 2: Banana, 3: Carrot, 4: Apple, 5: Date Note: there are two Apples

but sync(['Apple', 'Date']) -> 1: Apple, 4: Date

and syncWithoutDetaching(['Apple', 'Date']) -> 1: Apple, 2: Banana, 3: Carrot, 4: Date

sync(Array, false) is the same as syncWithoutDetaching():

public function syncWithoutDetaching($ids)
    {
        return $this->sync($ids, false);
    }

In short, by default sync() detaches.

Crompton answered 24/10, 2022 at 14:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.