Magento 1 – Call getMinimalPrice() on Single Product Entity with Tier Prices

magento-1modelpriceproducttierprice

I want to display the minimal tier price on my product page and wherever I load my product model. I am using the basic function to get price data:

$this->getPriceHtml($product, true);

When this is called on the product collection (such as a category page) it works fine. When I call getPriceHtml on a product model instance (loaded with Mage::getModel('catalog/product')->load($id), if I dump the product data then getData('minimal_price') does not exist.

I'm thinking that when loading the collection,

 ->addMinimalPrice()

is added to the collection, but this is missing from the single entity load. Therefore my question is, do I need to include some other method/helper/model when loading product in order for the minimal price to also be loaded?

Best Answer

I didn't find a simple method to load the index for a single product, the safest bet should be using a collection.

This helper method worked for me:

/**
 * Loads minimal price from index in single product entity
 *
 * @param Mage_Catalog_Model_Product $product
 * @return $this
 */
public function loadPriceIndex(Mage_Catalog_Model_Product $product)
{
    $productCollection = $product->getCollection();
    $productCollection->addAttributeToSelect([])
        ->addAttributeToFilter('entity_id', $product->getId())
        ->addPriceData();
    $product->addData($productCollection->getFirstItem()->getData());
    return $this;
}

Don't worry about database load, this results in a single query with only one join on the price index table like this:

SELECT `e`.*, price_index.price AS `indexed_price`, `price_index`.`price`, `price_index`.`final_price`,
    IF(`price_index`.`tier_price`,
        LEAST(`price_index`.`min_price`, `price_index`.`tier_price`), 
        `price_index`.`min_price`
    ) AS `minimal_price`,
    `price_index`.`min_price`, `price_index`.`max_price`, `price_index`.`tier_price`
FROM `catalog_product_entity` AS `e`
INNER JOIN `catalog_product_index_price` AS `price_index`
ON price_index.entity_id = e.entity_id
    AND price_index.website_id = '5'
    AND price_index.customer_group_id = 0
WHERE (`e`.`entity_id` = '2026') 
Related Topic