问题
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