12

I'm using Magento 2.1.0 and I'm currently having difficulties in filtering product collection with multiple categories. I've used more than a couple of ways to make it work but it won't.

Assuming:

$catalog_ids = [618, 619, 620];
  1. Returns NULL

    $productCollection = $this->productCollectionFactory->create()
        ->addAttributeToSelect('*')
        ->addCategoriesFilter(array('in' => $catalog_ids));
    
  2. Returns exception: Invalid attribute name: category_id

    $productCollection = $this->productCollectionFactory->create()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('category_id', array(
            'finset' => $catalog_ids
        ));
    
  3. Returns Syntax error or access violation

    $productCollection = $this->productCollectionFactory->create()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('category_ids', array(
            'finset' => $catalog_ids
        ));
    

Any advice on how I could be able to have this work or have something link this work?

1
  • Try to check generated sql. $productCollection->getSelectSql(true); Sep 27, 2016 at 8:00

2 Answers 2

15

You are probably used to the "every method returns $this" paradigm from Magento 1. This is not the case anymore (at least not always).

Specifically, addCategoriesFilter() does not return anything and that's why you get null.

Change the code to:

$productCollection = $this->productCollectionFactory->create();
$productCollection->addAttributeToSelect('*');
$productCollection->addCategoriesFilter(array('in' => $catalog_ids));
2
  • 3
    To suggest that it is not the case anymore is probably stated too strongly. The function 'addCategoryFilter' (singular) in the same class does return $this; so adding the return value in 'addCategoriesFilter' has probably just escaped the attention of a developer. Sep 28, 2016 at 8:06
  • yeah, that would make sense too Sep 28, 2016 at 8:14
5

Your first try is definitely the right way of doing it:

$values = [318, 619, 620];
$conditionType = "in";
$productCollection->addCategoriesFilter([$conditionType => $values]);

Now there's two things to ensure: $productCollection must be an instance of Magento\Catalog\Model\ResourceModel\Product\Collection for this to work (or from a class that extends it).

And obviously you need to have products in the catalog_category_product table that matches that condition, maybe that's not the case and that's why you get NULL.

2
  • Which is the better way using product collection or using service contracts? Magento\Catalog\Api\Data\ProductSearchResultsInterface
    – MagePsycho
    Sep 27, 2016 at 19:30
  • @MagePsycho if you have the choice always go for service contracts ;) Sep 27, 2016 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.