Search code examples
shopwareshopware6

How delete a property by groupId in product table?


I want delete a specific property by groupId in product table. I try this example, but it does not work :

$this->productRepository->delete([
   [
     'productId' => $productId,
     'properties' => [
         [
           'groupId' => $propertyGroupId
         ]
      ]
   ]
], Context::createDefaultContext());

Solution

  • You'll first need to fetch all option ids associated with the product and filtered by the group id. Once you have those you can build a payload to delete all product_property mappings. Since the mapping has two primary keys, you'll have to provide both the optionId and the productId to delete the mappings.

    $context = Context::createDefaultContext();
    $criteria = new Criteria([$productId]);
    $criteria->addAssociation('properties');
    $criteria->addFilter(new EqualsFilter('properties.groupId', $propertyGroupId));
    
    /** @var ProductEntity|null $product */
    $product = $container->get('product.repository')->search($criteria, $context)->first();
    
    $payload = $product->getProperties()->map(function (PropertyGroupOptionEntity $option) use ($productId) {
        return ['optionId' => $option->getId(), 'productId' => $productId];
    });
    
    $container->get('product_property.repository')->delete($payload, $context);