1

I'm trying to order products by position in category

public function __getProductCollection($category_id_array) {

    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect('*');
    $collection->addCategoriesFilter(['in' => $category_id_array]);
    $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
    $collection->addAttributeToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
    //$collection->addAttributeToSort('position');
    $collection->setOrder('position','ASC');
    

    return $collection;
}

I got this error

 Unknown column 'cat_index_position' in 'order clause'

I tried also

$collection->setOrder('cat_index_position','ASC');

$collection->setOrder('cat_index.position','ASC');

But the ordering is not working

PS: i'm using Magento 2.2.4

3
  • Try $collection->getSelect()->reset(Zend_Db_Select::ORDER)->order('position', 'ASC'); if it helps! Commented Jun 18, 2020 at 15:44
  • 1
    @Bhaumik1987 i think position doesn't exist on the product collection i solved the problem, you can see my solution below Commented Jun 18, 2020 at 16:07
  • @Bhaumik1987 I got this error Uncaught Error: Class 'Wetag\CarouselNamePlate\Block\Widget\Zend_Db_Select' not found Commented Jun 18, 2020 at 16:14

1 Answer 1

1

I solved the problem

i added a class attribute _categoryFactory and used it in constructor

public function __construct(
\Magento\Catalog\Block\Product\Context $context
,\Magento\Catalog\Model\CategoryFactory $categoryFactory) {
    parent::__construct(
            $context, $data
    );
    $this->_categoryFactory = $categoryFactory;
}



public function __getProductCollection($category_id) {

    $products = $this->_categoryFactory->create()->load($category_id)->getProductCollection()->addAttributeToSelect('*')->setOrder('cat_index_position','ASC');
    return $products;
}

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.