Magento产品集合不包括类别



我需要从我的产品集合中排除一个类别,但我不知道如何实现这一点。

要求:

  • 仅可见产品
  • 排序者: created_at DESC
  • 排除类别 ID 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')))

发现了这些类似的问题,但它们不能解决我的问题。

如何从 magento getCollection 中排除类别

Magento - 如何从产品系列中排除类别?

尝试以下代码:

$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

希望会有所帮助!

扩展 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

最新更新