Magento产品按类别划分

时间:2010-06-17 14:16:37

标签: php magento

我尝试通过此代码获取productsCollection:

    $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(array(4,5))不起作用,我看到了所有产品,即使在某些类别中也没有。

有什么问题?

2 个答案:

答案 0 :(得分:2)

尝试使用逗号分隔的ID传递字符串:

->addIdFilter("4,5")

如果这不起作用,您可以尝试:

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

答案 1 :(得分: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();