2013-02-10 126 views
0

我正在撰寫一個模塊,爲我加載特色產品列表。所有特色產品都坐在自己的類別+隱藏類別「特色」。該腳本返回一個錯誤。Magento:按兩種類別篩選產品集合

在分類視圖(list.phtml)我呼籲gettopproducts.phtml(工作正常):

<?php $currentCategory = Mage::registry('current_category'); ?> 
<?php $_products = $this->getTopProducts($currentCategory); ?> 
<?php echo $this->__('Available products: ').$_products->count(); ?> 

gettopproducts.phtml我調用一個函數的Gettopproducts.phpgetTopProducts()使電流類別。在Gettopproducts.php我有這樣的:

public function getTopProducts($currentCategory) 
{ 
    $_productCollection = Mage::getResourceModel('reports/product_collection') 
    ->addAttributeToSelect('*') 
    ->addCategoryFilter($currentCategory) 
    ->addAttributeToFilter('category_ids',array('finset'=>'87')); 
    $_productCollection->load(); 
    return $_productCollection; 
} 

該行:->addAttributeToFilter('category_ids',array('finset'=>'87'));應該添加第二個類別過濾器(以下簡稱「特色」類別的ID)。但是,當我使用這個,我得到一個錯誤。當我刪除這一行:->addAttributeToFilter('category_ids',array('finset'=>'87'));它完美的作品。

我使用的Magento 1.7.2

回答

1

我發現了原因。對於Magento 1.4+,類別ID不是reports/product_collection的成員。

這是怎樣的方式獲得它: 取代->addAttributeToFilter('category_ids',array('finset'=>'87')); 有:

$_productCollection->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left'); 
$_productCollection->addAttributeToFilter('category_id', array('in' => array('finset' => '87'))); 

因此,代碼如下所示:

$_productCollection = Mage::getResourceModel('reports/product_collection'); 
$_productCollection->addAttributeToSelect('*'); 
$_productCollection->addCategoryFilter($currentCategory); 
$_productCollection->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left'); 
$_productCollection->addAttributeToFilter('category_id', array('in' => array('finset' => '87')));   
$_productCollection->load(); 
return $_productCollection; 
0

對於Magento的1.7,這是對我來說是什麼在起作用:

$collection = Mage::getModel('catalog/product')->getCollection() 
    ->addAttributeToSelect('id')   
    ->addAttributeToFilter('visibility', 4) 
    ->addAttributeToFilter('home_slider', array('neq' => '')) 
    ->addAttributeToFilter('home_slider_value', $slide_num) 
    ->addStoreFilter(); 
    //here pass an array() of CATEGORY IDs 
    $catids = array('id_1,id_2, etc..'); 

    $statements = array(); 
    foreach ($catids as $categoryId){ 
     if (is_numeric($categoryId)){ 
     $statements[] = "{{table}}.category_id = $categoryId"; 
     } 
    } 

    $collection->distinct(true) 
    ->joinField('category_id','catalog/category_product', null,'product_id = entity_id', implode(" OR ",$statements),'inner');