Получите цену настраиваемых опций продукта


Мне нужно экспортировать все товары с ценами из Magento 1.7.

Для простых продуктов это не проблема, но для настраиваемых продуктов у меня есть эта проблема: Экспортируемая цена - это цена, установленная для соответствующего простого продукта! Как вы знаете, Magento игнорирует эту цену и использует цену настраиваемого продукта плюс корректировки для выбранных опций.

Я могу получить цену родительского продукта, но как мне рассчитать разницу в зависимости от выбранные параметры?

Мой код выглядит примерно так:

foreach($products as $p)
   {
    $price = $p->getPrice();
            // I save it somewhere

    // check if the item is sold in second shop
    if (in_array($otherShopId, $p->getStoreIds()))
     {
      $otherConfProd = Mage::getModel('catalog/product')->setStoreId($otherShopId)->load($p->getId());
      $otherPrice = $b2cConfProd->getPrice();
      // I save it somewhere
      unset($otherPrice);
     }

    if ($p->getTypeId() == "configurable"):
      $_associatedProducts = $p->getTypeInstance()->getUsedProducts();
      if (count($_associatedProducts))
       {
        foreach($_associatedProducts as $prod)
         {
                            $p->getPrice(); //WRONG PRICE!!
                            // I save it somewhere
                        $size $prod->getAttributeText('size');
                        // I save it somewhere

          if (in_array($otherShopId, $prod->getStoreIds()))
           {
            $otherProd = Mage::getModel('catalog/product')->setStoreId($otherShopId)->load($prod->getId());

            $otherPrice = $otherProd->getPrice(); //WRONG PRICE!!
                            // I save it somewhere
            unset($otherPrice);
            $otherProd->clearInstance();
            unset($otherProd);
           }
         }
                     if(isset($otherConfProd)) {
                         $otherConfProd->clearInstance();
                            unset($otherConfProd);
                        }
       }

      unset($_associatedProducts);
    endif;
  }
Author: Marius, 2013-10-18

4 answers

Вот как вы можете узнать цены на простые продукты. Пример приведен для одного настраиваемого продукта, но вы можете интегрировать его в свой цикл.
Может возникнуть проблема с производительностью, потому что существует много циклов foreach, но, по крайней мере, у вас есть с чего начать. Вы можете оптимизировать позже.

//the configurable product id
$productId = 126; 
//load the product - this may not be needed if you get the product from a collection with the prices loaded.
$product = Mage::getModel('catalog/product')->load($productId); 
//get all configurable attributes
$attributes = $product->getTypeInstance(true)->getConfigurableAttributes($product);
//array to keep the price differences for each attribute value
$pricesByAttributeValues = array();
//base price of the configurable product 
$basePrice = $product->getFinalPrice();
//loop through the attributes and get the price adjustments specified in the configurable product admin page
foreach ($attributes as $attribute){
    $prices = $attribute->getPrices();
    foreach ($prices as $price){
        if ($price['is_percent']){ //if the price is specified in percents
            $pricesByAttributeValues[$price['value_index']] = (float)$price['pricing_value'] * $basePrice / 100;
        }
        else { //if the price is absolute value
            $pricesByAttributeValues[$price['value_index']] = (float)$price['pricing_value'];
        }
    }
}

//get all simple products
$simple = $product->getTypeInstance()->getUsedProducts();
//loop through the products
foreach ($simple as $sProduct){
    $totalPrice = $basePrice;
    //loop through the configurable attributes
    foreach ($attributes as $attribute){
        //get the value for a specific attribute for a simple product
        $value = $sProduct->getData($attribute->getProductAttribute()->getAttributeCode());
        //add the price adjustment to the total price of the simple product
        if (isset($pricesByAttributeValues[$value])){
            $totalPrice += $pricesByAttributeValues[$value];
        }
    }
    //in $totalPrice you should have now the price of the simple product
    //do what you want/need with it
}

Приведенный выше код был протестирован на CE-1.7.0.2 с образцами данных Magento для 1.6.0.0.
Я протестировал продукт Zolof Разрушитель рок-н-ролла: LOL Cat Футболка и она сшивается, чтобы работать. Я получаю в результате те же цены, что и во внешнем интерфейсе, после настройки продукта с помощью Size и Color

 13
Author: Marius, 2014-02-10 07:27:10

Может быть, вам нужно изменить $p на $prod в приведенном ниже коде?

 foreach($_associatedProducts as $prod)
         {
                            $p->getPrice(); //WRONG PRICE!!
 3
Author: Francis Kim, 2014-02-07 15:47:32

Вот как я это делаю:

$layout = Mage::getSingleton('core/layout');
$block = $layout->createBlock('catalog/product_view_type_configurable');
$pricesConfig = Mage::helper('core')->jsonDecode($block->getJsonConfig());

Кроме того, вы можете преобразовать его в Varien_Object:

$pricesConfigVarien = new Varien_Object($pricesConfig);

Поэтому в основном я использую тот же метод, который используется для расчета цен на вашу настраиваемую страницу продукта в ядре magento.

 2
Author: Oleg Kudinov, 2015-02-10 11:59:37

Не уверен, поможет ли это, но если вы добавите этот код в настраиваемый.страница phtml на ней должны быть указаны настраиваемые супер-атрибуты продуктов с ценой каждого варианта и его меткой.

   $json =  json_decode($this->getJsonConfig() ,true);


    foreach ($json as $js){
        foreach($js as $j){

      echo "<br>";     print_r($j['label']); echo '<br/>';

            foreach($j['options'] as $k){
                echo '<br/>';     print_r($k['label']); echo '<br/>';
                print_r($k['price']); echo '<br/>';
            }
        }
    }
 0
Author: Egregory, 2014-02-07 15:42:40