How to assign categories to Product entity via DAL

Hi Guys!

I’m starting with developing Shopware modules and probably I don’t understand everything yet, and because of that, I’ve stuck. Maybe someone will be able to help me.

I’m trying to assign/unassign the product categories via DAL. At first, I’ve tried to set categoryTree key in the update function, but it’s read-only field.

Then I’ve tried to use product_category repository for managing entities there, but when I try to search items by specific criteria I’m getting the error that is described here.

Which repository or what entity should I use to assign or unassign the categories to the product via DAL? Maybe there is a function in ProductEntity that I don’t see?

Thank you!

Here is an example, how you can do it:

$this->productRepository->update(
    [
        [
            'id' => $productId,
            'categories' => [
                [ 'id' => $categoryId ]
            ]
         ]
     ],
     $context);

I have an article with some more examples on my Shopware 6 blog How to assign categories to products programmatically in Shopware 6? - Shopwarian.com. Hope this helps. :slight_smile:

1 „Gefällt mir“

Thank you! I’ve tried to use categories key, but I didn’t know that the categories there must be structured with ['id' => 'XXX'] array. After changing that everything works fine!

Do you know, how in a such approach unassign the specific category? It looks that this approach could be only used for adding the categories, but not for removing.

Removing categories from the product is quite simple, just use the product_category repository like this:

$this->productCategoryRepository->delete([['productId' => $productId, 'categoryId' => $categoryId]], $event->getContext());

This is something, that more people might be struggling with, so I have added an article on my Shopware 6 blog with some more detailed info and examples: How to remove products from categories programmatically in Shopware 6? - Shopwarian.com.

Thank you! That works :slight_smile: