从多个类别中获取产品

时间:2014-04-09 04:03:21

标签: magento magento-1.7

我正在尝试从多个类别中获取产品,而我正在使用

 $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

请帮我收集不同的信息。

2 个答案:

答案 0 :(得分:1)

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

所以在你的代码结束时添加这个

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

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

我不记得究竟是什么是表别名。

答案 1 :(得分: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.
相关问题