0

I'm trying to get product collection by Multiple Category Ids with Multiple SKUs. The result has been coming wrong. I can't understand where I'm wrong. The code is given below

<?php

namespace CustomVendor\CustomModule\Block\Specific;

class Collection extends \Magento\Framework\View\Element\Template{

protected $_productCollectionFactory;
protected $helperFactory;
protected $listProductBlock;
private $request;
protected $_categoryFactory;
protected $_attributeFactory;
protected $_productListHelper;

/**
 * @var \Magento\Framework\Registry
 */
protected $_coreRegistry;


/**
 * @param \Magento\Framework\Registry
 */
    
public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory,        
    \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
    \Magento\Catalog\Block\Product\ListProduct $listProductBlock,  
    \Magento\Catalog\Helper\ImageFactory $helperFactory,
    \Magento\Framework\App\Request\Http $request,
    \Magento\Catalog\Model\CategoryFactory $categoryFactory,
    \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attributeFactory,
    \Magento\Framework\Registry $registry,
    array $data = []
)
{    
    $this->_attributeFactory = $attributeFactory;
    $this->_categoryFactory = $categoryFactory;
    $this->categoryCollectionFactory = $categoryCollectionFactory;
    $this->_productCollectionFactory = $productCollectionFactory;
    $this->listProductBlock = $listProductBlock;
    $this->helperFactory = $helperFactory;
    $this->request =$request;
    $this->_coreRegistry = $registry;
    parent::__construct($context, $data);
}

public function getProductCollection()
{

    $price=$this->getRequest()->getParam('price');
    $cat=$this->getRequest()->getParam('cat');
    $sortby=$this->getRequest()->getParam('product_list_order');
    if(empty($sortby)){
       $sortby='position';
    }
    $listdesc=$this->getRequest()->getParam('product_list_dir');
    
    $page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
       //get values of current limit
    //$pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 3;
    $pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 12;
    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->addCategoriesFilter(['in' => array(3,4)]);
    $collection->addAttributeToFilter('sku', ['in' => array('1709529','880998', '555555','111111','222222')]);

    
    $collection->setOrder('title','ASC');
    $collection->setPageSize($pageSize);
    $collection->setCurPage($page);

    $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
    $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);

    //echo "<pre>"; print_r($collection->getData()); exit();

    return $collection;
}

public function getImage($product)
{
 // for image url get
  return  $this->helperFactory->create()->init($product, 'product_thumbnail_image')->resize(150)->getUrl();       
}
protected function _prepareLayout()
{
    parent::_prepareLayout();
    //$this->pageConfig->getTitle()->set(__('products'));

    //$post = $this->_coreRegistry->registry('current_post');
    //echo "collection Product"; echo "<pre>"; print_r($post->getData());
    if ($this->getProductCollection()) {
    $toolbar = $this->getLayout()
               ->createBlock(
            'Magento\Catalog\Block\Product\ProductList\Toolbar',
            'product_list_toolbar'
            )
            ->setTemplate('CustomVendor_CustomModule::product/list/toolbar.phtml')
            ->setCollection($this->getProductCollection());

        // $pager = $this->getLayout()->createBlock(
        //     'Magento\Theme\Block\Html\Pager',
        //     'CustomModule.product.pager'
        // )->setAvailableLimit(array(3=>3,6=>6,9=>9))->setShowPerPage(true)->setCollection(
        //     $this->getProductCollection()
        // );
        $pager = $this->getLayout()->createBlock(
            'Magento\Theme\Block\Html\Pager',
            'CustomModule.product.pager'
        )->setAvailableLimit(array(12=>12,24=>24,36=>36))->setShowPerPage(true)->setCollection(
            $this->getProductCollection()
        );
        $this->setChild('pager', $pager);
        $this->setChild('toolbar', $toolbar);
        $this->getProductCollection()->load();
    }
    return $this;
}
public function getPagerHtml()
{
    return $this->getChildHtml('pager');
}
public function getToolbarHtml()
{
    return $this->getChildHtml('toolbar');
}
public function getMode()
{
    return $this->getChildBlock('toolbar')->getCurrentMode();
}


public function getProductImageUrl($product)
{
   // return $this->_image->init($product, 'category_page_grid')->constrainOnly(FALSE)
   //      ->keepAspectRatio(TRUE)
   //      ->keepFrame(FALSE)
   //      ->getUrl();

    return $this->helperFactory->create()->init($product, 'category_page_grid')->constrainOnly(FALSE)
        ->keepAspectRatio(TRUE)
        ->keepFrame(FALSE)
        ->getUrl();

}


public function getAddToCartPostParams($product)
{
    return $this->listProductBlock->getAddToCartPostParams($product);
}

}

I have tried to show the proper result of Product collection by googling a lot of times. But there is no proper solution that I haven't got in google. It will be helpful and grateful if this type of task has been figured out. Thank You.

5
  • You're trying to get the product's from category 3 and category 4 or the category inside category 3 and 4? And also how is the result wrong? Dec 23, 2021 at 8:37
  • Better you can check your query using this code echo $collection->getSelect();exit; you can add this line after //echo "<pre>"; print_r($collection->getData()); exit(); Dec 23, 2021 at 8:39
  • I'm trying to get product list from Category 3 and Category 4 and Category 5, .... like array(3,4,5,....) with Multiple SKUSs, not from the category inside Category 3 and 4. Dec 23, 2021 at 8:42
  • Hi Jitendra, I have tested with your given code, $collection->getSelect(). I want to get all products of Category 3, 4, 5 ,... with multiple SKUs, not common part. Here the query is WHERE (cat.category_id IN('3', '4'))))) AND (e.sku IN('880981', '880998', '1692971', '1709529', '1718933', '1733375', '878771', '878802', '889607', '555555', '111111', '222222')) ... like that. I can't understand how to all products from cat 3,4,5,...with multiple SKUs. Thank U for quick reply. Dec 23, 2021 at 9:10
  • ok. this query part(cat.category_id IN('3', '4'))))) fetching all the products of category 3 OR 4 but after adding this query part IN('880981', '880998', '1692971', '1709529', '1718933', '1733375', '878771', '878802', '889607', '555555', '111111', '222222')) you are restricting query selection result from this sku list. If you want all products from category 3 or 4 then comment second sku condition & check. Dec 23, 2021 at 11:08

1 Answer 1

0

Actually you pass the category ids array in addCategoriesFilter(['in' => $cat_ids]) that's why the error occur. Just Replace my code with yours:

$cat_ids = "3,4";
$collection->addAttributeToSelect('*')->addAttributeToSort('position', 'ASC')->addCategoriesFilter(['in' => $cat_ids])->addAttributeToFilter('sku', array('1709529','880998', '555555','111111','222222'));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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