Magento 2 – Filter Product Collection by Multiple Categories

collection;filtermagento-2.1magento2product-collection

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?

Best Answer

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));