Laravel Eloquent -连接与不分离的同步

uinbv5nw  于 2022-11-18  发布在  其他
关注(0)|答案(3)|浏览(107)

在Laravel中,syncWithoutDetaching和attach之间有什么区别?

jjjwad0x

jjjwad0x1#

假设您的数据透视表中有自动递增的主键id,您会注意到:

  1. attach()会将新记录添加到数据透视表中,而先前存在的关系将获得新的ID。
  2. sync()将移除所有现有的关系,并仅设置当前请求中提供的关系,同时使用新的ID。
  3. syncWithoutDetaching()不会删除当前进程中提供的关系中缺少的所有现有关系,则先前存在的行不会获得新的ID。
3vpjnl9f

3vpjnl9f2#

两件事:

  1. attach()将始终向数据透视表添加新记录,而syncWithoutDetaching()仅在记录不存在时添加新记录。
    假设您有订单和项目。
$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()返回null,而syncWithoutDetaching()返回一个数组,显示附加/分离/更新的内容。
pn9klfpd

pn9klfpd3#

attach()将添加新记录,即使它们已经存在。sync()将删除sync()中不存在的记录,保留那些已经存在的记录,并添加那些不存在的记录。syncWithoutDetaching()sync()相同,但不删除任何内容。
所以

1: Apple, 2: Banana, 3: Carrot

attach(['Apple', 'Date'])-〉1: Apple, 2: Banana, 3: Carrot, 4: Apple, 5: Date注意:有两个苹果
但是sync(['Apple', 'Date'])-〉1: Apple, 4: Date
以及syncWithoutDetaching(['Apple', 'Date'])-〉1: Apple, 2: Banana, 3: Carrot, 4: Date
sync(Array, false)syncWithoutDetaching()相同:

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

简而言之,默认情况下sync()分离。

相关问题