2013-10-18 172 views
0

我需要從我的productCollection中排除一個類別,但我不知道如何實現這一目標。Magento產品收集排除類別

要求:

  • 唯一可見的產品
  • 排序:created_at DESC
  • 排除類別編號43
  • 限4(產品)

要找回我的收藏我使用以下代碼:

$collection = Mage::getResourceModel('catalog/product_collection') 
       ->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds()); 



$collection = $this->_addProductAttributesAndPrices($collection) 
        ->addAttributeToSort('created_at', 'DESC') 
        ->setPageSize(4) 
        ->setCurPage(1); 

這工作得很好,但我不能添加此過濾器:

->addFieldToFilter('category_id', array('nin' => array('43'))) 

我發現這些類似的問題,但他們不會解決我的問題。

How to exclude a category from a magento getCollection

Magento - How do I exclude a category from product collection?

回答

4

試試下面的代碼:

$collection = Mage::getResourceModel('catalog/product_collection');   
$collection->addAttributeToFilter('status', 1); // Enable products 
$collection->addAttributeToFilter('visibility', 4); // Visible products 
$collection->addAttributeToSort('created_at', 'DESC') // Order by created_at DESC 
      ->setPageSize(4) // Number of products 
      ->setCurPage(1); // set page size 
$catId = 43; // category id to exclude 
$collection->getSelect()->join(array('cats' => 'catalog_category_product'), 'cats.product_id = e.entity_id'); // Join with category on product/entiry id 
$collection->getSelect()->where('cats.category_id!=?',$catId); // exclude category from collection 

echo '<pre>'; 
echo $collection->getSelect(); // See sql query 
print_r($collection->getData()); Print collection in array format 

希望能幫助!

+0

感謝您的回覆,但它不工作。我有以下例外情況:在/lib/Varien/Data/Collection.php:373'上已經存在具有相同ID「6130」的消息'Item(Mage_Catalog_Model_Product)'異常'Exception' –

+0

更改' $ collection'到'$ customCollection'中的每一個代碼。 –

+0

仍然不起作用,同樣的錯誤!我正在使用magento 1.7.0.2版本 –

0

對拉吉夫的答案的Martijn擴大不包括GROUP BY,一個完整的工作的例子是:

$collection = Mage::getResourceModel('catalog/product_collection');   
$collection->addAttributeToFilter('status', 1); // Enable products 
$collection->addAttributeToFilter('visibility', 4); // Visible products 
$collection->addAttributeToSort('created_at', 'DESC') // Order by created_at DESC 
     ->setPageSize(4) // Number of products 
     ->setCurPage(1); // set page size 
$catId = 43; // category id to exclude 
$collection->getSelect()->join(array('cats' => 'catalog_category_product'), 'cats.product_id =   e.entity_id'); // Join with category on product/entiry id 
$collection->getSelect()->where('cats.category_id!=?',$catId); // exclude category from collection 
$collection->getSelect()->group(array('e.entity_id')) // Group by e.entity_id to prevent Item with the same id already exists.. Exception 

echo '<pre>'; 
echo $collection->getSelect(); // See sql query 
print_r($collection->getData()); Print collection in array format 
+0

完美的作品,我不得不添加尾隨;到組數組,但它的工作。謝謝! – 2016-12-31 05:42:35