2014-01-14 133 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/>"; 
}