Search code examples
symfonycriteriashopware

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


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());

Solution

  • 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());