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')
            ->load();
  • What issue you are facing here? – aman Sep 14 at 7:18
  • @aman going to php session close function – Masud Shaikh Sep 14 at 7:20
up vote 3 down vote accepted

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->addAttributeToSelect('*');
 $collection->addCategoriesFilter(['nin' => $categories]);
 $collection->setPageSize(10)
 print_r($collection->getData());
  • 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 – Masud Shaikh Sep 14 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 – aman Sep 14 at 7:32
  • Its worked thanks @aman – Masud Shaikh Sep 14 at 7:40

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

to

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')],
                'cat.product_id'
            )->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;
    }
  • It is worked fine Thanks! @amit – Masud Shaikh Sep 14 at 7:41

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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