Magento - > addCategoryFilter - 按根类别过滤产品集合

Mar*_*ive 6 magento

关于在产品集合中使用- > addCategoryFilter.为什么不能按根类别过滤?我有2个商店,都有不同的根类别.我想在我的主页上显示畅销产品列表.但我无法按照根类别过滤产品,只能根据该类别过滤子类别.

因此,在我的主页上,两家商店的所有产品都会显示出来.我可以通过任何子类别过滤ok.例如,我的第二个根类别的ID为35.如果我尝试按此过滤,我会从两个根获得每个产品.但是该根下的第一个子类别是ID 36,并且通过此过滤可以正常工作,仅显示那些产品.我的电话如下(简化):

$_category = Mage::getModel('catalog/category')->load(35);

$_testproductCollection = Mage::getResourceModel('catalog/product_collection')
->addCategoryFilter($_category)
->addAttributeToSelect('*');
$_testproductCollection->load();

foreach($_testproductCollection as $_testproduct){ 
echo $this->htmlEscape($_testproduct->getName())."<br/>"; 
};
Run Code Online (Sandbox Code Playgroud)

任何人都知道为什么这不起作用?或者是否有其他方法可以根据根类别进行过滤?

更新: 我还没有运气.似乎非常错误 - 使用根类别添加类别过滤器有时只能工作,您需要将所有产品添加到根,然后保存,然后删除不应该在该根cat中的任何产品,然后重新保存.但如果你重新索引,你会再次展示所有产品.如果我从上面的集合调用输出sql查询,我得到以下内容:

SELECT `e`.*, `cat_index`.`position` AS `cat_index_position`, `price_index`.`price`, `price_index`.`tax_class_id`, `price_index`.`final_price`, IF(`price_index`.`tier_price`, LEAST(`price_index`.`min_price`, `price_index`.`tier_price`), `price_index`.`min_price`) AS `minimal_price`, `price_index`.`min_price`, `price_index`.`max_price`, `price_index`.`tier_price` FROM `catalog_product_entity` AS `e` INNER JOIN `catalog_category_product_index` AS `cat_index` ON cat_index.product_id=e.entity_id AND cat_index.store_id='2' AND cat_index.category_id='35' INNER JOIN `catalog_product_index_price` AS `price_index` ON price_index.entity_id = e.entity_id AND price_index.website_id = '1' AND price_index.customer_group_id = 0
Run Code Online (Sandbox Code Playgroud)

如您所见,该类别列在那里,为什么过滤器不起作用?

Mar*_*ive 16

好吧,我认为这样做,没有测试太多,但似乎已经完成了这个伎俩.您需要首先获取商店根类别ID,然后加入一些字段,以便您可以访问产品"category_id",然后使用以下内容进行过滤:

$_rootcatID = Mage::app()->getStore()->getRootCategoryId();

$_testproductCollection = Mage::getResourceModel('catalog/product_collection')
->joinField('category_id','catalog/category_product','category_id','product_id=entity_id',null,'left')
->addAttributeToFilter('category_id', array('in' => $_rootcatID))
->addAttributeToSelect('*');
$_testproductCollection->load();

foreach($_testproductCollection as $_testproduct){ 
    echo $this->htmlEscape($_testproduct->getName())."<br/>"; 
};
Run Code Online (Sandbox Code Playgroud)