2013-08-05 47 views
1

我顯示的產品在我的homepage之上有'選定'屬性爲'是'。Magento addAttributeToFilter不工作?

到目前爲止我試着:

$_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錯了,但我不知道如何。任何幫助,將不勝感激!

謝謝!

回答

3

Soooooo ....因爲您的屬性是下拉菜單,所以您無法使用eq =「是」執行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); 

也許有一個更乾淨的方式來做到這一點 - 但這是我所做的。

+0

非常感謝您的詳細回覆。但是,這太麻煩了。我可以使用其他屬性類型,例如文本或是/否。我應該使用哪個代碼來簡化代碼? –

+0

嗨,我剛在這裏找到了一個更好的答案:http://stackoverflow.com/questions/16968501/correct-usage-of-addattributetofilter-in-magento感謝您的幫助! –