Magento 2 sort collection by given ids

Today we discuss how in Magento 2 sort collection by give ids. Sometime we need to get product collection by given ids form example random ids 5,4,13. We take the example of product collection and filter it by give ids. You can use this on any kind of collection like order collection, category collection and any custom collection too. So here is our example.

protected $_productCollectionFactory;
public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
    ) {
         $this->_productCollectionFactory = $productFactory;
    }
    public function getProductCollection()
    {
        $productIds=array(9,21,5,3);
        $productCollection = $this->_productCollectionFactory->create();
        $productCollection->getSelect()->order(new \Zend_Db_Expr('FIELD(entity_id,' . implode(',', $productIds).')'));
        return $productCollection;
     
     }

Note: You can sort any collection following this example.

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

One thought on “Magento 2 sort collection by given ids

  1. It works for me

    $collection->getSelect()->order(new \Zend_Db_Expr(‘FIELD(e.entity_id,’ . implode(‘,’, $this->featureProductsArray).’)’));

    Whole code is

    $collection = $this->_productCollectionFactory->create();
    $collection->addAttributeToSelect(‘*’);
    $collection->addFieldToFilter(‘sku’,[‘in’ => $featureProductsArray]);
    $collection->addAttributeToFilter(‘visibility’, \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
    $collection->addAttributeToFilter(‘status’,\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
    $collection->addStoreFilter($storeId);
    $collection->getSelect()->order(new \Zend_Db_Expr(‘FIELD(e.entity_id,’ . implode(‘,’, $this->featureProductsArray).’)’));
    $items = $collection->load();

Leave a Reply