2

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();
2
  • What issue you are facing here? Sep 14, 2018 at 7:18
  • @aman going to php session close function Sep 14, 2018 at 7:20

2 Answers 2

3

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());
2
  • 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 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 Sep 14, 2018 at 7:32
1

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;
    }
0

Your Answer

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

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