Magento filter product collection by multiple categories

前端 未结 6 1722
故里飘歌
故里飘歌 2020-12-09 13:56

Is there an easy way to filter a product collection by multiple categories? To get all items in any of the listed categories? addCategoryFilter doesn\'t seem to

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 14:20

    • Magento 1.8.0.0;
    • Flat catalog enabled in admin;
    • Make sure you've cached the block in which you'll place this;
    • Don't add this in paid themes ..
    • The inner join hard-coded here reproduces this:

      $collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());

      without 'cat_index.category_id=2'

    $category = Mage::getModel('catalog/category')->load(100);
    $allChildsIds = $category->getAllChildren($category);
    
    $visibility = Mage::getModel('catalog/product_visibility');
    
    $collection = Mage::getResourceModel('catalog/product_collection');
    $collection = $this->_addProductAttributesAndPrices($collection)
      ->addStoreFilter()
      ->setFlag('do_not_use_category_id', true)
      ->setFlag('disable_root_category_filter', true)
      ->addAttributeToSort('created_at', 'desc');
    
    $whereCategoryCondition = $collection->getConnection()
      ->quoteInto('cat_index.category_id IN(?) ', $allChildsIds);
    $collection->getSelect()->where($whereCategoryCondition);
    
    $conditions = array();
    $conditions[] = "cat_index.product_id = e.entity_id";
    $conditions[] = $collection->getConnection()
      ->quoteInto('cat_index.store_id = ? ', Mage::app()->getStore()->getStoreId());
    $conditions[] = $collection->getConnection()
      ->quoteInto('cat_index.visibility IN(?) ', $visibility->getVisibleInCatalogIds());
    
    $collection->getSelect()->join(
      array('cat_index' => $collection->getTable('catalog/category_product_index')),
      join(' AND ', $conditions),
      array()
    );
    
    $collection
      ->setPageSize(3)
      ->setCurPage(1);
    
    $collection->load();
    

提交回复
热议问题