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];
-
Returns NULL
$productCollection = $this->productCollectionFactory->create() ->addAttributeToSelect('*') ->addCategoriesFilter(array('in' => $catalog_ids));
-
Returns exception: Invalid attribute name: category_id
$productCollection = $this->productCollectionFactory->create() ->addAttributeToSelect('*') ->addAttributeToFilter('category_id', array( 'finset' => $catalog_ids ));
-
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 getnull
.Change the code to: