:::: MENU ::::
Posts tagged with: order collection

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(at_status_default.entity_id,' . implode(',', $productIds).')'));
      return $productCollection;
     
     }

Note: You can sort any collection following this example.

Author: Qaisar Satti
Category: Magento 2
Last Modified: February 7, 2018


Magento 2 get single column values from collection

Today we learn about how to get single column values from collection. For this example we use the product collection to get names of product. You can get product collection by following the Magento 2 get product collection.

protected $_productCollectionFactory;

public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productFactory
    ) {
        $this->_productCollectionFactory = $productFactory;
    }
    public function getProductCollection()
    {
      $productCollection = $this->_productCollectionFactory->create();
      return $productCollection->getColumnValues(name);
     
     }

Note: You can use same method with any collection.

Author: Qaisar Satti
Category: Magento 2
Last Modified: December 19, 2017