0

I want to get the max price of all products using product collection. I tried the below but it didn't work

$collection = $this->_productFactory->create()
            ->getCollection()
            ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left')
            ->addAttributeToSelect('*')
            ->addAttributeToFilter('status', 1)
            ->setOrder('price', 'ASC')
            ->addAttributeToFilter('visibility', 4)
            ->getFirstItem();

        print_r($collection->getPrice());

How to get max price and min price of products from product collection in magento 2?

2

Half answer already answered by @hitesh. you can get min and max price from product collection

$maxPrice = $collection->getMaxPrice();
$minPrice = $collection->getMinPrice();

Reference

| improve this answer | |
  • I didnt get...using $collection->getMaxPrice or getMinPrice().. – Pavithra Nov 22 '18 at 6:52
  • remove this line ->getFirstItem(); it will load first product object. – Qaisar Satti Nov 22 '18 at 6:54
1

Use addAttributeToSort() function for sorting product collection by price.

$collection->setOrder('price', 'DESC');

Change to

$collection->addAttributeToSort('price', 'DESC');
| improve this answer | |
  • It didnt work... – Pavithra Nov 22 '18 at 6:52
1
        $productCollection = $this->_productCollectionFactory->create();
        $productCollection->addAttributeToSelect('price');
        $productCollection->setOrder('price', 'DESC');
        $minPrice=$productCollection->getMinPrice();
        $maxPrice=$productCollection->getMaxPrice();
| improve this answer | |

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.