我需要从productCollection中排除一个类别,但我不知道如何实现这一目标。
要求:
要检索我的收藏,请使用以下代码:
$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?
答案 0 :(得分: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
希望会有所帮助!
答案 1 :(得分:0)
扩展Rajiv的答案,因为Martijn没有包括该组,一个完整的例子是:
$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