Magento – Why sort by price order not working

magento2product-collectionsorting

I am using below script to desc order price collection but it's not working.

This collection is working for a simple product but configurable products not working:

    $productsCollection->addFinalPrice()->addMinimalPrice()->addAttributeToSort('price',"desc");
                        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
foreach ($productsCollection as $product) {
                /*print_r($product->getData());*/
                $productModel = $objectManager->create('Magento\Catalog\Model\Product');
                $product = $productModel->load($product->getEntityId());
                $attributeOptions = [];
                $getChildId = [];
                $configurable = [];
                $attributeVariant = '';
                if($product->getTypeId() != 'simple' && $product->getTypeId() != 'virtual') {
                    /*if(!$product Instanceof \Magento\Catalog\Model\Product){
                        continue;
                    }*/
                    $productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
                    foreach ($productAttributeOptions as $productAttribute) {
                        $configurable[] = ['id' => $productAttribute['id'],
                                'value' => $productAttribute['label']];
                        $attributeVariant = $productAttribute['label'];
                        foreach ($productAttribute['values'] as $attribute) {
                            $attributeOptions[$productAttribute['label']][] = [
                                    'id' => $attribute['value_index'],
                                    'value' => $attribute['store_label']];
                        }
                        $_configChild = $product->getTypeInstance()->getUsedProducts($product);

                        $attributeCode = $productAttribute['attribute_code'];
                        foreach ($_configChild as $child) {
                            /*print_r($child->getData());*/
                            $originalPrice = $child->getPrice() == '' ? 0 : $child->getPrice();
                            $finalPrice = $child->getSpecialPrice() == '' ? 0 : $child->getSpecialPrice();
                            $percentage = 0;
                            if ($originalPrice > $finalPrice) {
                                $percentage = number_format(($originalPrice - $finalPrice) * 100 / $originalPrice,0);
                            }
                            $quantityChild = $this->stockManagerInterface->getStockQty($child->getId(), $child->getStore()->getWebsiteId());
                            $getChildId[] = ['id' => $child->getId(),
                                    'sku' => $child->getSku(),
                                    'name' => $child->getName(),
                                    'quantity' => $quantityChild == '' ? 0 : $quantityChild,
                                    'base_price' => $child->getPrice() == '' ? 0 : $child->getPrice(),
                                    'price' => $child->getFinalPrice() == '' ? 0 : $child->getFinalPrice(),
                                    'attribute_code' => $child->getData($attributeCode) == '' ? '' : $child->getData($attributeCode),
                                    'image' => $this->getMediaUrl()."catalog/product".$child->getImage(),
                                    'url' => $child->getProductUrl(),
                                    'discount' => $percentage
                                ];
                            }
                        }
                    }
                    $quantity =  (int)$this->stockManagerInterface->getStockQty($product->getId(), 1);
                    $outOfStock =  $product->getData('is_in_stock');
                    if($product->getTypeId() == 'simple'  ||  ($product->getTypeId() == 'configurable'  && count($getChildId) > 0)) {
                        $originalPrice = $product->getPrice() == '' ? 0 : $product->getPrice();
                        $finalPrice = $product->getSpecialPrice() == '' ? 0 : $product->getSpecialPrice();
                        $percentage = 0;
                        if ($originalPrice > $finalPrice) {
                            $percentage = number_format(($originalPrice - $finalPrice) * 100 / $originalPrice,0);
                        }
                        $currentProduct = ['id' => $product->getId(),
                            'sku' => $product->getSku(),
                            'name' => $product->getName(),
                            'configurable-options' => $configurable,
                            'attribute-variant' => $attributeVariant,
                            'quantity' => $quantity>0 ? $quantity : 0,
                            'base_price' => $product->getPrice() == '' ? 0 : $product->getPrice(),
                            'price' => $product->getFinalPrice() == '' ? 0 : $product->getFinalPrice(),
                            'outof-stock' => $outOfStock,
                            'type' => $product->getTypeId(),
                            'attribute' => (object)$attributeOptions,
                            'image' => $this->getMediaUrl()."catalog/product".$product->getImage(),
                            'url' => $product->getProductUrl(),
                            'child' => ($getChildId),
                            'pagination' => ceil($productsCollection->getSize() / 20),
                            'discount' => $percentage
                        ];
                        $categoriesArrays[$i] = $currentProduct;

                        $i++;
                    }
                }

If it's not an asc or desc what is the problem here?

Best Answer

For Me below code works fine

 $productsCollection->setOrder('price','ASC'); //DESC for decending 
Related Topic