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?

3 Answers 3

2

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

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

Reference

2
  • I didnt get...using $collection->getMaxPrice or getMinPrice()..
    – Pavithra
    Nov 22, 2018 at 6:52
  • remove this line ->getFirstItem(); it will load first product object. Nov 22, 2018 at 6:54
1

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

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

Change to

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.