0

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

要求:

  • 仅可见产品
  • 订购者: 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 - 如何从产品集合中排除一个类别?

4

2 回答 2

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

希望会有所帮助!

于 2013-10-18T07:54:40.357 回答
0

由于 Martijn 不包括 group by,因此扩展 Rajiv 的答案,一个完整的工作示例是:

$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
于 2014-09-18T08:43:00.787 回答