如何在Laravel syncWithoutDetaching中与2个主要项目同步



Cart_product表有4列:

id | cart_id | product_id | size_id | quantity

其中belongsToManyCartProductSize的关系。

用户可以添加不同尺寸但不相同尺寸的产品,因此产品->id=1可以具有大小->id=1并且大小->id=2。

我想同步产品->id和大小->id,其中只有1行相同的产品->id和大小->id。

使用此代码,只有我的产品->id已同步。

$this->cart->products()->syncWithoutDetaching(
[$product->id => ['size_id' => $size->id, 'quantity' => $quantity]]
);

正如我所说,我需要同步产品->id和大小->id,我可以有不同尺寸的产品:

id | cart_id | product_id | size_id | quantity
1  | 1       |1           | 2       |2
2  | 1       |1           | 3       |1

但不是相同尺寸的产品:

id | cart_id | product_id | size_id | quantity
1  | 1       |1           | 2       |2
2  | 1       |1           | 2       |1

我已经检查了许多案例作为:

$this->cart->products()->syncWithoutDetaching(
[$product->id, $size->id => ['quantity' => $quantity]]
);

但这不可能是真正的结果!

BelongsToMany关系是为只有两个外键作为其唯一性索引的透视表创建的。在您的情况下,唯一性是通过三个索引cart_idproduct_idsize_id获得的,因此您不能使用关系中的任何预定义方法来实现目标。

附带说明:我建议您在数据库中添加此约束,这样,如果您的代码试图在这些索引中插入具有相同值的两行,就会触发错误

要与三个索引同步,我建议您使用updateOrInsert()upsert()

DB::table('your_pivot_table_name')->updateOrInsert(
['cart_id' => 1, 'product_id' => 1, 'size_id' => 2], //the unique index to look out for
['quantity' => 2] //the other fields to sync
);

另一个想法是将数据透视表声明为Custom Intermediate table Models;sync";使用CCD_ 10对其进行

编辑:追加

DB::table('cart_product')->upsert(
[
[ 'cart_id' => $this->instance()->id, 'product_id' => $product->id, 'size_id' => $size->id, 'quantity' => (int) $qunatity]
], 
['cart_id', 'product_id', 'size_id'], 
['quantity']
);

最新更新