【问题标题】:Apply two conditionals to a singel attribute in a Magento collection将两个条件应用于 Magento 集合中的单个属性
【发布时间】:2011-02-04 16:25:59
【问题描述】:

我目前正在尝试在 Magento 中获取特定价格范围的产品。我尝试了我能想到的前两种合乎逻辑的方式。第一个是在我的代码中添加两个 addAttributeToFilter() 语句。

$products->addAttributeToFilter('price', array('gteq' => $r['price_low']));
$products->addAttributeToFilter('price', array('lteq' => $r['price_high']));

没有骰子。这只是给了我第二个。

然后我决定尝试将两个条件添加到单个 addAttributeToFilter() 中,如下所示:

$price_array['gteq'] = $r['price_low'];
$price_array['lteq'] = $r['price_high'];
$products->addAttributeToFilter('price', $price_array);

再次只是高端。我在我的集​​合上做了一个 getSelect() 并在查询中确认它只应用高端。

有谁知道我如何才能获得具有价格范围的产品。

【问题讨论】:

    标签: php magento


    【解决方案1】:

    这是我最终完成这项工作所要做的(感谢 Alan Storm!--在 Magento 网站上的指南中找到)。

    if($has_low_price && $has_high_price) {
        $products->addFieldToFilter('price', array('gteq' => $r['price_low']));
        $products->addFieldToFilter('price', array('lteq' => $r['price_high']));
    } elseif($has_high_price) {
        $products->addAttributeToFilter('price', array('lteq' => $r['price_high']));
    } elseif($has_low_price) {
        $products->addAttributeToFilter('price', array('gteq' => $r['price_low']));
    } else {
    
    }
    

    如果你想做 AND,你必须使用 addFieldToFilter 而不是 addAttributeToFilter。

    【讨论】:

      【解决方案2】:

      你快到了。我相信您正在寻找的语法是这样的:

      $filter = array(
          array("gteq" => $r['price_low']),
          array("lteq" => $r['price_high']),
      );
      
      $products->addAttributeToFilter("price", $filter);
      

      这不是很直观,但很有效。

      希望有帮助!

      谢谢, 乔

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-11-01
        • 1970-01-01
        • 2020-02-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-01
        • 1970-01-01
        相关资源
        最近更新 更多