2014-01-14 242 views
5

我想获得一个产品集合的产品在A类或B类。我已经能够成功地把这些产品用下面的PHP代码:过滤产品收集Magento的1.7

$collection = Mage::getModel('catalog/product') 
    ->getCollection() 
    ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left') 
    ->addAttributeToFilter('category_id', array('in' => array('finset' => 4,19))) 
    ->addAttributeToSelect('*'); 

但是,如果该产品是在这两个类别4和19,则显示错误:

Item (Mage_Catalog_Model_Product) with the same id "173" already exist 

这是因为集合有重复的行了。我努力寻找合适的代码来过滤出集合中的任何重复行。解决方案必须是对值进行分组,或者使用不同的值,但我不确定如何前进。

又见Filter Magento collection but not products, using distinct

回答

13

好吧,我有这个解决由于https://stackoverflow.com/a/13291759/991491

$collection = Mage::getModel('catalog/product') 
    ->getCollection() 
    ->joinField('category_id', 'catalog/category_product', 'category_id', 'product_id = entity_id', null, 'left') 
    ->addAttributeToFilter('category_id', array('in' => array('finset' => 3,4))) 
    ->addAttributeToSelect('*'); 
$collection->getSelect()->group('e.entity_id'); 

集团条款确实在克服得到返回重复的产品ID的把戏。

+2

这个固定为我'$收藏 - >不同的(真正的);' –

+0

你能告诉我该文件的完整路径编辑? –

+0

我不确定你的意思。没有真正的文件路径要编辑,因为这是我自己的代码中的文件,在我自己的插件中。 –

1

我得到这个错误,什么Magento的通过/ VAR报告/报告/ XXXXXXX是:

a:5:{i:0;s:71:"Item (Mage_Catalog_Model_Product) with the same id "xxx" 

我所做的是停用产品,这个ID,并固定。所以我删除这个产品并重新创建它。不是一个完美的解决方案,但现在工作。 但仍然想知道那里有什么问题?关于这个“独特”的解决方案,对我来说,这个错误突然而来,我们并没有改变或开发出最近可能导致这种情况的新事物。任何人都知道为什么突然发生这种情况?

+0

你可以把你的SQL查询放在这里吗?这可能会提供一些见解 –

0

过滤器产品系列使用多个类别ID

$all_categories = array('3','13','113'); 
$productCollection = Mage::getModel('catalog/product')->getCollection(); 
$productCollection->joinField('category_id', 'catalog/category_product', 'category_id', 
        'product_id = entity_id', null, 'left') 
        ->addAttributeToSelect('*') 
        ->addAttributeToFilter('type_id', array('eq' => 'simple')) 
        ->addAttributeToFilter('category_id', array($all_categories)); 
foreach($productCollection as $product) 
{ 
    echo $product->getId() .$product->getName() . "<br/>"; 
}