2010-06-17 123 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();