How to add new crossSellings to Shopware 6 product in a Controller?

Viewed 478

I have a dictionary of product id's linked to other product id's. For each product I want to create new cross-sellings (of lists of products) using the id's from the relationship mentioned above. Is it possible to update the product cross-sellings in a controller?
Should it be done through update method or anything else?

$this->productRepository->update([$productData], Context::createDefaultContext());

Update or Upsert does not seem to do anything to the product either.

 $crossSellingData = [
    'id' => $crossSellingIds[0],
    'name' => 'First Cross Selling',
    'position' => 1,
    'type' => 'productList',
    'active' => true,
    'assignedProducts' => [
        [
            'productId' => "5f5365e2adb446f6958faa4257c0af6d",
            'position' => 1
        ]
    ],
];
$productRepository->upsert([['id' => $productId, 'crossSelling' => $crossSellingData]], Context::createDefaultContext());
2 Answers

You can do so by using the productCrossSellingRepository (Table: product_cross_selling) instead.

$newCrossSelling = [
    'productId' => $mainProductId,
    'active' => true,
    'name' => 'First Cross Selling',
    'type' => 'productList',
    'position' => 1,
    'assignedProducts' => [
        [
            'productId' => $firstCrossSellingProductId,
            'position' => 1,
        ],
        [
            'productId' => $secondCrossSellingProductId,
            'position' => 2,
        ],
    ]
];

$this->productCrossSellingRepository->create([$newCrossSelling], Context::createDefaultContext());

It should also be possible to add the cross-sellings over the product repository. I see two problems in your original code:

  1. The association is named crossSellings, you use crossSelling, because there is no field named crossSelling, the repository ignores that key, that's way your update has no effect
  2. The association is a too many association, that means the repository expects a list of crossSellings instead of one crossSelling.

So these minor changes in your original upsert call should fix your problem:

$productRepository->upsert([['id' => $productId, 'crossSellings' => [$crossSellingData]]], Context::createDefaultContext());

Note the trailing s in the name of the crossSelling-Association and the extra [] array around the crossSellingData

Related