Laravel Eloquent - 附加与 SyncWithoutDetaching

Laravel Eloquent - Attach vs. SyncWithoutDetaching

Laravel中syncWithoutDetaching和attach有什么区别?

两件事:

  1. attach() 将始终向数据透视表添加一条新记录 table,而 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() returns null,而 syncWithoutDetaching() returns 数组显示了 attached/detached/updated.

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

  1. attach() 会将新记录添加到数据透视表 table,并且先前存在的关系将获得新的 ID。
  2. sync() 将删除所有存在的关系并设置仅在当前请求中提供,也有新的 ID。
  3. syncWithoutDetaching() 将删除除当前进程中提供的所有现有关系,然后预先存在的行将不会获得新的 ID。