在Laravel中,syncWithoutDetaching和attach之间有什么区别?
jjjwad0x1#
假设您的数据透视表中有自动递增的主键id,您会注意到:
id
attach()
sync()
syncWithoutDetaching()
3vpjnl9f2#
两件事:
$order->items()->attach(1); $order->items()->attach(1); // $order->items()->count() === 2 $order2->items()->syncWithoutDetaching(1); $order2->items()->syncWithoutDetaching(1); // $order2->items()->count() === 1
null
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: Datesync(Array, false)与syncWithoutDetaching()相同:
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)
public function syncWithoutDetaching($ids) { return $this->sync($ids, false); }
简而言之,默认情况下sync()分离。
3条答案
按热度按时间jjjwad0x1#
假设您的数据透视表中有自动递增的主键
id
,您会注意到:attach()
会将新记录添加到数据透视表中,而先前存在的关系将获得新的ID。sync()
将移除所有现有的关系,并仅设置当前请求中提供的关系,同时使用新的ID。syncWithoutDetaching()
不会删除当前进程中提供的关系中缺少的所有现有关系,则先前存在的行不会获得新的ID。3vpjnl9f2#
两件事:
attach()
将始终向数据透视表添加新记录,而syncWithoutDetaching()
仅在记录不存在时添加新记录。假设您有订单和项目。
attach()
返回null
,而syncWithoutDetaching()
返回一个数组,显示附加/分离/更新的内容。pn9klfpd3#
attach()
将添加新记录,即使它们已经存在。sync()
将删除sync()
中不存在的记录,保留那些已经存在的记录,并添加那些不存在的记录。syncWithoutDetaching()
与sync()
相同,但不删除任何内容。所以
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()
相同:简而言之,默认情况下
sync()
分离。