【问题标题】:Magento addAttributeToFilter not working?Magento addAttributeToFilter 不起作用?
【发布时间】:2013-08-05 03:53:33
【问题描述】:

我在我的homepage 上显示具有“已选择”属性为“是”的产品。

到目前为止我尝试过:

$_productCollection = Mage::getModel('catalog/product') -> getCollection()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('selected',array('eq'=>'Yes'))
    ->setVisibility(array(2,3,4))
    ->setOrder('created_at', 'desc')
    ->setPage(1, 48);

还有:

$_productCollection = Mage::getResourceModel('catalog/product_collection')
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('selected',array('eq'=>'Yes'))
    ->setVisibility(array(2,3,4))
    ->setOrder('created_at', 'desc')
    ->setPage(1, 48);

但如您所见,“没有符合选择的产品。”但是有几种产品我已将“选定”属性设置为“是”。

我的属性截图:http://postimg.org/gallery/53wrrrhe/

但是当我摆脱这条线时:

->addAttributeToFilter('selected',array('eq'=>'Yes'))

从他们那里,他们都工作正常,并按预期提供所有产品。

我的看法是我写错了这个 addAttributeToFilter 但我不知道怎么写。任何帮助将不胜感激!

谢谢!

【问题讨论】:

    标签: magento


    【解决方案1】:

    Soooooo.... 因为您的属性是一个下拉列表,所以您不能使用 eq = “Yes” 执行 addAttributeToFilter。属性“selected”的值是其存储在数据库中的选项的数值。可以是任何数字。

    你要做的就是这个……

    找出哪个选项是“是”选项。

    $option_id = 0;
    $options = Mage::getModel("eav/entity_attribute_option")
      ->getCollection()
      ->setStoreFilter()
      ->join("attribute", "attribute.attribute_id = main_table.attribute_id", "attribute_code")
      ->addFieldToFilter("attribute_code", array("eq" => "selected"));
    
    foreach ($options as $option)
      if ($option->getValue() == "Yes")
        $option_id = $option->getOptionId();
    

    然后您可以使用"eq" => $option_id 执行上述操作。

    $_productCollection = Mage::getModel('catalog/product') -> getCollection()
        ->addAttributeToSelect('*')
        ->addAttributeToFilter('selected',array('eq'=> $option_id))
        ->setVisibility(array(2,3,4))
        ->setOrder('created_at', 'desc')
        ->setPage(1, 48);
    

    也许有一种更简洁的方法可以做到这一点——但这就是我所做的。

    【讨论】:

    • 非常感谢您的详细回复。然而,这太繁重了。我可以使用其他属性类型,例如文本或是/否。我应该使用哪个来简化代码?
    • 嗨,我刚刚在这里找到了一个更简洁的答案:stackoverflow.com/questions/16968501/… 感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    相关资源
    最近更新 更多