2014-04-09 115 views
0

我试图从多个类别获取产品,我使用从多个类别获取产品

$category_collection = Mage::getModel('catalog/category')->getCollection() 
       ->addAttributeToSelect('*') 
       ->addAttributeToFilter('name', array('like' => '%'.$searchstring.'%')) 
       ->load(); 

foreach ($category_collection as $category) { 
    $ids[] = $category->getId(); 
} 

$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' => $ids))) 
     ->addAttributeToSelect('*') 
     ->setPageSize(5); 

,但它显示错误Item (Mage_Catalog_Model_Product) with the same id "2" already exist

请帮助我获得不同的集合。

+0

你过滤CATEGORY_ID通过提供产品ID。 –

+0

不,我从类别ID阵列过滤产品 –

+0

嗯,你好像已经更新了代码。 –

回答

0

我得到的代码: -

// Code to Search Product by $searchstring and get Product IDs 
    $category_collection = Mage::getModel('catalog/category')->getCollection() 
      ->addAttributeToSelect('*') 
      ->addAttributeToFilter('name', array('like' => '%' . $searchstring . '%')) 
      ->load(); 

    foreach ($category_collection as $category) { 
     $category_id = $category->getId(); 
     $collection = Mage::getResourceModel('catalog/product_collection'); 
     $collection->addCategoryFilter($category); //category filter 
     $collection->addAttributeToFilter('status', 1); //only enabled product 
     $collection->addAttributeToFilter('visibility', 4); 
     $collection->addAttributeToSelect('*'); //add product attribute to be fetched   
     $collection->addStoreFilter(); 
     foreach ($collection as $_product): 
      $ids[] = $_product->getId(); 
     endforeach; 
    } 
    $ids = array_unique($ids); 
    $html = ''; 
    foreach ($ids as $_ids): 
     $product = Mage::getModel('catalog/product')->load($_ids); 
     $html .= '<img name="'.$product->getPrice().'" alt="'.$product->getName().'" draggable="true" ondragstart="drag(event)" id="' . $product->getId() . '" class="ui-widget-content ui-draggable" src="' . $product->getImageUrl() . '" width="50px" height="50px" />'; 
    endforeach; 
    echo $html; 

$ids will return unique id and in foreach we can load product. 
1

尝试通过语句添加组。您获得重复的产品是因为您在多个类别中拥有相同的产品,并且您的代码会检索它们两次(至少),并且一个集合不支持具有相同ID的项目。

因此,在你的代码的末尾添加此

$collection->getSelect()->group('e.entity_id'); 

$collection->getSelect()->group('main_table.entity_id'); 

我不记得到底是什么表的别名。

+0

它不起作用 –

相关问题