【问题标题】:Magento Checkout count weight of products which match attributeMagento Checkout 计算匹配属性的产品的重量
【发布时间】:2015-03-15 12:58:39
【问题描述】:

我需要计算结账时有多少特定类型的产品。但只有(!)特定类型的产品。类型在下拉属性中定义。

这是一个计算重量的代码,效果很好。 \template\checkout\cart.phtml

<?php $items = Mage::getSingleton('checkout/session')->getQuote()->getAllItems();
$weight = 0;
foreach($items as $item) {
    $weight += ($item->getWeight() * $item->getQty()) ;
}
echo $weight;
?>

但是如何只统计具有特定属性值的产品呢?

喜欢 => "只计算属性 color = green 的产品"

我发现了很多关于收集和过滤的信息,但它似乎不适用于购物车项目。

希望你能帮助我。

【问题讨论】:

    标签: magento count checkout


    【解决方案1】:

    您必须在循环时加载产品模型(昂贵),然后您可以像这样调用它的属性:

    foreach( $oItems as $oItem )
    {
        $oProduct = $oItem->getProduct();
        $oProductModel = Mage::getModel( 'catalog/product' )->load( $oProduct->getId() );
        // For code...
        $sColor   = $oProductModel->getData( 'color' );
        var_dump( $sColor );
        // For text...
        $sFormat  = $oProductModel->getAttributeText( 'color' );
        var_dump( $sFormat );
    }
    

    【讨论】:

    • 我将您的方法与@Hatef 的答案结合起来,然后运行起来。谢谢
    【解决方案2】:

    这是获取属性值的方法(加载产品后):

     $product = $item->getProduct();
     $value = $product->getAttributeText($yourAttributeCode);
    

    但请注意,为了工作,您需要在属性编辑器中将:'在产品列表中显示''在产品列表中使用' 设置为是管理面板。


    对于分组部分,一种可能的方法是这样做(仅当您的特定属性具有少量值时才有意义):

    $weights = array ('redWeight' => 0, 'blueWeight' => 0, 'yellowWeight' => 0, ..);
    $groupRed = array();
    $groupGreen = array();
     ...
    
    foreach($items as $item) {
      $product = $item->getProduct();
      $value = $product->getAttributeText('yourAttributeCode');
      $weight = ($item->getWeight() * $item->getQty());
      if($value){ //Do all products have this attribute?
        Switch($value){
           case "red":
               $Weights['redWeight'] += $weight;
               $groupRed[] = $item;
               break;
           case "green":  
              ....
         }
      } else {
        continue;
       } 
    }
     ....
      HERE YOU HAVE GROUPS OF YOUR ITEMS ACCORDING TO THEIR SPECIFIC ATTRIBUTE VALUES
    

    【讨论】:

    • 我使用了@vladimir 的答案,他描述了如何加载产品并将其与您的方法相结合。但我跳过了数组。比它奏效了。谢谢!
    • @MartinSt 注意加载不必要的模型。当您循环浏览您的项目时,产品模型应该已经加载,您不必再次加载它。这些繁重的模型(查询)可能会在未来显着降低您网站的性能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    相关资源
    最近更新 更多