如何在 Laravel 中同步同一属性的多个值?

Riz*_*han 4 php mysql database-relations laravel laravel-5.4

我使用 Laravel 5.4 开发了一个电子商务(具有多个产品属性功能)网站。一切正常。但是当我尝试在数据透视表中同步同一属性的多个值时。Laravel 忽略重复的 pares。例如,我有一个名为“网络”的属性,它有 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
Run Code Online (Sandbox Code Playgroud)

我想将产品属性存储在“ProductAttributes”表中。但是 Laravel 忽略其中之一。

我正在保存这样的数据:

    $product = Product::create([
        'name' => 'Test Mobile'
    ]);

    $product->attributes()->sync([
        1 => ['AttributeValue' => '3G'], 
        1 => ['AttributeValue' => '4G']
    ]);
Run Code Online (Sandbox Code Playgroud)

任何建议,想法?

小智 10

我知道这已经晚了两年,但我今天正在处理同样的问题,并认为我可以将解决方案留在这里,以防将来有人寻找它。如果您使用原始代码:

    $product->attributes()->sync([
        1 => ['AttributeValue' => '3G'], 
        1 => ['AttributeValue' => '4G']
    ]);
Run Code Online (Sandbox Code Playgroud)

数组中的第二项将覆盖第一项,因此最终数据库中将只有“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'], 
    ]);

Run Code Online (Sandbox Code Playgroud)

这是非常低效的,因为它需要一个查询来从关系中删除所有现有数据,然后一项一项地添加新项目。您也可以syncWithoutDetaching在循环内部运行,整体效率低下在很大程度上取决于您需要同步的项目数量。

2)第一个解决方案不够好,所以我不断挖掘和试验,并想出了如何实现这一点的方法。您可以发送没有给出特定索引的数组,并将 ID 放在数组本身中,而不是将您的项目放在数组中的特定索引上。像这样的东西

    $product->attributes()->sync([
        ['AttributeID' => 1, 'AttributeValue' => '3G'], 
        ['AttributeID' => 1, 'AttributeValue' => '4G']
    ]);

Run Code Online (Sandbox Code Playgroud)

通过这样做,您实际上可以将两个相同的项目发送AttributeID到 sync() 方法,而不会一个覆盖另一个

  • 但 Laravel 5.7 仍然存在问题。将挖掘更多并更新 (2认同)