Correct usage of addAttributeToFilter in Magento

余生颓废 提交于 2020-01-02 06:59:28

问题


I'm having issues filtering a product collection with a customer attribute using 'addAttributeToFilter.' I have a dropdown menu attribute with the options 'yes' and 'no' and I'd like to to show only a list of products with the attribute set to 'yes.' I'm currently using:

public function getReleasesCollection() {
$products = Mage::getModel('catalog/product')->getCollection() ->addAttributeToFilter('preorder', array ('eq' => 1)) ->addAttributeToSelect('name') ->addAttributeToSelect('releasedate');

However this does not return any products.

I have also tried using:

->addAttributeToFilter('manufacturer', 1);

->addAttributeToFilter('manufacturer', '1');

->addAttributeToFilter('manufacturer', 'Yes);

->addAttributeToFilter('manufacturer', array('eq' => '1'));

->addAttributeToFilter('manufacturer', array('eq' => 'Yes'));

I am able to filter by any other attribute such as name, sku, description, etc. but I'm unable to filter with my custom attribute.

Any pointers?


回答1:


<?php 

class LSC_ReleaseCalendar_Block_Calendar extends Mage_Core_Block_Template 
{    
    public function getReleasesCollection()
  { 
        $preorderAttribute = 'preorder';
        $preorderValue = 'yes';
        $products = Mage::getModel('catalog/product')->getCollection()  
            ->addAttributeToSelect('*')
            ->addFieldToFilter(
                $preorderAttribute,
                    array(
                        'eq' => Mage::getResourceModel('catalog/product')
                            ->getAttribute($preorderAttribute)
                            ->getSource()
                            ->getOptionId($preorderValue)
                )
            );
        foreach ($products as $product) {
            echo $product->getName();
            echo $product->getReleaseDate();
        }
    }

}

gist link



来源:https://stackoverflow.com/questions/16968501/correct-usage-of-addattributetofilter-in-magento

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!