Magento - Loading root collection loads all products
Regarding using multiple stores, with different root categories:
I have 2 stores set up, with different roots. One has 14 products, the other 6.
If I use the following on my homepage (simply to show how many products are in the root category for that store - in this case with an ID of 8) I get 20 products - so all products in the store, from all roots:
$_testproductCollection = Mage::getModel('catalog/category')->load(8)
->getProductCollection()
->addAttributeToSelect('*')->load();
echo "NO. OF PRODUCTS IS ".$_testproductCollection->count();
However, if I change the ID to a sub-category, I get the correct amount of products. There are only 6 products in this root:
But the count shows 20 (as there's 20 in the whole store - or both roots).
Anyone know what's up? Is it a bug?
I also noticed that if you go to Manage Products and use the store view filter, it doesn't do anything, still showing 20 products i开发者_运维问答n the store view whose root has only 6 products:
OK, I think this works, haven't tested too much but seems to have done the trick. You need to first get your stores root category id, then join some fields so you have access to the products "category_id", then filter using that:
$_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/>";
};
精彩评论