0

How to set if condition in magento 2 with product collection?

 public function getCategoryProducts($categoryId) 
    {
        $products = $this->getCategoryData($categoryId)->getProductCollection()->$products->addAttributeToSelect('*');
        echo $products->getSelect()->setOrder(IF('cat_index_position' = '0',1,0));exit;
        return $products;
    }

How to give if condition in above collection?

Above IF condition not working in collection and throws error for syntax error.

Thanks.

7
  • try adding quotes in front of IF and at the end of your expression – Marius Jun 16 '16 at 12:59
  • plz give me your answer i am not understand your sentance – Rakesh Jesadiya Jun 16 '16 at 13:00
  • try with $products->getSelect()->setOrder("IF('cat_index_position' = '0',1,0)");exit; – Marius Jun 16 '16 at 13:04
  • main.CRITICAL: Zend_Db_Select_Exception: Unrecognized method 'setOrder()' in /var/www/html/candleshack/vendor/magento/zendframework1/library/Zend/Db/Select.php:1339 – Rakesh Jesadiya Jun 16 '16 at 13:08
  • try order instead of setOrder – Marius Jun 16 '16 at 13:11
1

Its working solution based on marius comment,

public function getCategoryProducts($categoryId) 
    {
        $products = $this->getCategoryData($categoryId)->getProductCollection();
        $products->addAttributeToSelect('*')->setPageSize(14);
        $products->getSelect()->order("IF('cat_index_position' = '0',true,false)");

        return $products;
    }

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.