Home > Software engineering >  Cannot filter products by multiple tags in Shopware 6
Cannot filter products by multiple tags in Shopware 6

Time:11-29

A little background before my question:

A product has multiple tags lets say 6 tags, and we want to filter products where 2 out of those 4 tags are present, but only those product that have BOTH these 2 tags there. Is there a way we can do that using criteria ? An example filter request would be like such:

Select all products that have (TAG A and TAG B) OR (TAG C)

TAG-A|TAG-B,TAG-C

I already tried using EqualsAnyFilter but that selects like an OR where it filters products that have Tag A only - but I want it to be an AND filter. Using just EqualsFilter does not seem to be returning any products.

        $criteria = new Criteria();
        $criteria->addAssociation('tags');

        $orFilters = [];

        $orTags = explode(',', 'TAG-A|TAG-B,TAG-C'); // Based on above scenario

        foreach ($orTags as $orTag) {
            $andFilters = [];
            $andTags = explode('|', $orTag);
            
            // Attempt 1 with EqualsAnyFilter
            $andFilters[] = new EqualsAnyFilter('tags.name', $andTags);


            // Attempt 2 with EqualsFilter
            foreach ($andTags as $andTag) {
                $andFilters[] = new EqualsFilter('tags.name', $andTag);
            }


            if ($andFilters) {
                $orFilters[] = new AndFilter($andFilters);
            }
        }

        if ($orFilters) {
            $criteria->addFilter(new OrFilter($orFilters));
        }

But this does not return the desired result. Is there a way to filter products like this? Any suggestions are welcome. Thanks!

CodePudding user response:

I was able to figure it out as follows by using the ContainsFilter instead:

    foreach ($andTags as $andTag) {
        $andFilters[] = new ContainsFilter('tagIds', $andTag);
    }
  • Related