Shopware 6 - Tips, tricks and how to's

How to assign categories to products programmatically in Shopware 6?

In Shopware 6, you can assign as many categories, as you want, to any product, independently of the category level. This is apparent in the Administration, but what if you need to assign the categories programmatically in your plugin?

First of all, you need to have the IDs of the categories, that you want to assign to your product. You can get a category ID for example by getting it by its name from the category repository like this:

For some more information on repositories in Shopware 6 in general and how to get the mysterious “context” from the example, you can read my article here.

Assign a category to a product

So now that we have a category ID, we can assign it to a product. We need this product’s ID for this. You probably already have it available in your code and if not, then you can look for it in the product repository exactly the same way we have looked for the category ID in the category repository. That is all we need to assign a category to a product, so let’s do it:

And this is it – your product is assigned to your category. Although the data in reality are not saved just in the product table, you can save them using the product repository. Shopware 6 DAL takes care of handling the entity associations for you.

Assign multiple categories to a product

Similarly, we can assign a product to more categories. Let’s select more categories, this time by filtering them by a string, contained in their names:

So for example, if you had categories “Spare parts for cars” and “Spare parts for motorcycles” and you have searched for “spare parts”, now you have two category IDs, stored in an array. And this is how you assign them both to your product:

We have simply passed an array of category IDs in the correct format to the product repository and it has saved all the category associations to the product for us.

If you want to know the reverse process of category association, there is an article about how you can remove categories from a product in Shopware 6.