Product collection issue

$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');

products  = $productCollection->addAttributeToSelect('*')
            ->addCategoriesFilter('category_id', array(
                array('nin' => $currentCategoryId),
            ->setOrder('price', 'ASC')
  • What issue you are facing here? Commented Sep 14, 2018 at 7:18
  • @aman going to php session close function Commented Sep 14, 2018 at 7:20

2 Answers 2


To fetch product collection by categories you can try this code:

$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

 $categories = [2,3,5];//category ids array

 $collection = $productCollection ->create();
 $collection->addCategoriesFilter(['nin' => $categories]);
  • I have tried this code got the error message Fatal error: Allowed memory size of 805306368 bytes exhausted (tried to allocate 400592896 bytes) in Unknown on line 0 Commented Sep 14, 2018 at 7:28
  • Try the updated answer, as I limit the item to 10, seems it is printing lots of data so it went out of memory Commented Sep 14, 2018 at 7:32

First, you to have to check why the parameter is not working

If you check addCategoriesFilter function definition, then you will find it support a parameter which is an array. the parameter is a one-dimensional array which supports index as condition Type and value as filter value.Like

$categoriesFilter  =  
    'in' => [10,15],
    'nin' => [12,18]

So,you have to change

addCategoriesFilter('category_id', array(
                array('nin' => $currentCategoryId),


addCategoriesFilter(array('nin' => $currentCategoryId))

 public function addCategoriesFilter(array $categoriesFilter)
        foreach ($categoriesFilter as $conditionType => $values) {
            $categorySelect = $this->getConnection()->select()->from(
                ['cat' => $this->getTable('catalog_category_product')],
            )->where($this->getConnection()->prepareSqlCondition('cat.category_id', ['in' => $values]));
            $selectCondition = [
                $this->mapConditionType($conditionType) => $categorySelect
            $this->getSelect()->where($this->getConnection()->prepareSqlCondition('e.entity_id', $selectCondition));
        return $this;

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.