Upsert doesn't work correctly.

When adding a product using upsert it creates the product correctly. But trying to ‚update‘ the product using the the same method doesn’t work, as I get an integrity constraint, saying the following;
 

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'BU-10121' for key 'product.uniq.product.product_number__version_id'

I add products using the following code; 

$product = [
    'name' => (string) $product->name,
    'price' => [[
        'currencyId' => Defaults::CURRENCY,
        'gross' => 15,
        'net' => 10,
        'linked' => false
    ]],
    'manufacturer' => ['name' => 'Test'],
    'tax' => ['name' => '21%', 'taxRate' => 21],
    'stock' => (int) $product->qty,
    'id' => (string) $product->ean,
    'ean' => (string) $product->ean,
    'productNumber' => (string) $product->sku,
    'categories' => [
        ['Id' => 1, 'name' => (string) $product->type]
    ]
];

$this->productRepository->upsert([$product], Context::createDefaultContext());

How can i fix this?

1 „Gefällt mir“

I just had the same problem because I accidentally assigned a new random Uuid for upsert.

 'id' =\> Uuid::randomHex(),

Do you maybe have products with a different ean but with the same productNumber (sku)?

 

Also you should probably use a Uuid for your ID as it’s a BINARY(16) on database level. But I’m not sure about the side effects of using the ean as id.

You can use Uuid::fromStringToHex($ean) … it will hash the EAN and creates the same Uuid for the same EAN all the time. So your products will reliably get the same Uuid everytime.

So the upsert also works fine. You can simply specify the ‚id‘ => Uuid::fromStringToHex($ean) …

Rico

2 „Gefällt mir“