2010-06-17 124 views
1

我試圖通過這個代碼來獲得productsCollection:Magento的產品按類別

$collection = Mage::getModel('catalog/category')->getCollection(); 
/* @var $collection Mage_Catalog_Model_Resource_Eav_Mysql4_Category_Collection */ 
$collection->addAttributeToSelect('url_key') 
    ->addAttributeToSelect('name') 
    ->addAttributeToSelect('is_anchor') 
    ->addAttributeToFilter('is_active', 1) 
    ->addIdFilter(array(4,5))//$_categories) 
    ->setOrder('position', 'ASC') 
    ->joinUrlRewrite() 
    ->load(); 

$productCollection = Mage::getResourceModel('catalog/product_collection'); 
$layer    = Mage::getSingleton('catalog/layer'); 
$layer->prepareProductCollection($productCollection); 
$productCollection->addCountToCategories($collection); 
foreach($productCollection as $product){ 
    print_r($product->getCategoryIds()); 
} 

但線addIdFilter(陣列(4,5))不工作,我看到所有的產品,甚至沒有在一些的categorys。

出了什麼問題?

回答

2

試圖傳遞一個字符串以逗號分隔的ID:

->addIdFilter("4,5") 

如果不工作,你可以嘗試:

->addAttributeToFilter(’id’, array('in' => array(4,5))) 
0

這幫助我:

 $collection = $category->getCollection(); 
    /* @var $collection Mage_Catalog_Model_Resource_Category_Collection */ 
    $collection->addAttributeToSelect('url_key') 
     ->addAttributeToSelect('name') 
     ->addAttributeToSelect('all_children') 
     ->addAttributeToSelect('is_anchor') 
     ->addAttributeToFilter('is_active', 1) 
     ->addIdFilter($category->getChildren()) 
     ->setOrder('position', Varien_Db_Select::SQL_ASC) 
     ->joinUrlRewrite() 
     ->load();