我使用Laravel 5.4开发了一个电子商务(具有多个产品属性功能)网站。一切都很好。但是当我尝试在数据透视表中同步同一属性的多个值时。 Laravel忽略了重复的削减。例如,我有一个名为“网络”的属性,它有3个值:2G,3G,4G。移动设备支持3G和4G网络。我想在数据库中同步3G和4G值。 Laravel无视其中一个。
Products Table:
ID - Product Name
1 - Test Mobile
Attributes Table
ID - AttributeName
1 - Network
AttributeValues Table
ID - AttributeID - AttributeValue
1 - 1 - 2G
2 - 1 - 3G
3 - 1 - 4G
ProductAttributes Table
ID - AttributeID - ProductID - AttributeValue
1 - 1 - 1 - 3G
1 - 1 - 1 - 4G
我想将产品属性存储在“ProductAttributes”表中。但是Laravel忽略了其中一个。
我正在保存这样的数据:
$product = Product::create([
'name' => 'Test Mobile'
]);
$product->attributes()->sync([
1 => ['AttributeValue' => '3G'],
1 => ['AttributeValue' => '4G']
]);
任何建议,想法?
Laravel中的sync()
函数自动读取重复项。你可以强迫它
$product->attribute()->syncWithoutDetaching([
1 => ['AttributeValue' => '3G'],
1 => ['AttributeValue' => '4G']
]);
祝你好运伴侣!
使用sync方法使用以下关系在Controller中存储/更新数据:
$product-> attribute()->sync($request->input('product_ids', []));
我知道这已经晚了两年,但今天我正处理同样的问题,并且认为我可以在这里留下解决方案,以防万一有人在将来寻找它。如果您使用原始代码:
$product->attributes()->sync([
1 => ['AttributeValue' => '3G'],
1 => ['AttributeValue' => '4G']
]);
数组中的第二项将覆盖第一项,因此最后,数据库中只有一个“4G”条目。这实际上不是一个laravel问题,它是如何实现PHP关联数组的 - 你基本上不能在同一个索引上的数组中有两个项目。
实际上有两种方法可以解决这个问题
1)第一个是非常低效的,但它是功能性的。我将它留在这里只是为了记录,因为这是我解决问题的原始方式。而不是你的代码,你需要这样的东西
$product->attributes()->sync([]); // empty relation completely
// add first item
$product->attributes()->syncWithoutDetaching([
1 => ['AttributeValue' => '3G'],
]);
// add second item without detaching the first one
$product->attributes()->syncWithoutDetaching([
1 => ['AttributeValue' => '4G'],
]);
这非常低效,因为它需要一个查询来删除关系中的所有现有数据,然后逐个添加新项。你也可以在循环中运行syncWithoutDetaching
,整体效率低下很大程度上取决于你需要同步多少项。
2)第一个解决方案不够好,所以我不断挖掘和试验,并找到了如何实现这一目标的方法。您可以发送没有给定特定索引的数组,而不是将您的项目放在数组中的特定索引上,并将ID放入数组本身。像这样的东西
$product->attributes()->sync([
['AttributeID' => 1, 'AttributeValue' => '3G'],
['AttributeID' => 1, 'AttributeValue' => '4G']
]);
通过这种方式,您实际上可以使用相同的AttributeID
将两个项目发送到sync()方法,而不会覆盖另一个