In this blog, we will see some important function in magento product collection class.
Product Collection class in magento is Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection. Lets look at the important functions
Get All Products of a category
$collection
= Mage::getResourceModel(
'catalog/product_collection'
)
->setStoreId(
$this
->getStoreId())
->addCategoryFilter(
$category
);
Tn this the addCategoryFilter() function, is used to get all products of a particular category. So, if you want to get all products of a certain category use this function.
Visibility Filter
$collection
= Mage::getResourceModel(
'catalog/product_collection'
);
Mage::getSingleton(
'catalog/product_visibility'
)->addVisibleInCatalogFilterToCollection(
$collection
);
The addVisibleFilterToCollection() adds visibility filter to a product collection i.e only products which are visible in frontend. The product which have “Not Visible Individually” selected in admin are removed.
Status Filter
$collection
= Mage::getResourceModel(
'catalog/product_collection'
);
Mage::getSingleton(
'catalog/product_status'
)->addVisibleFilterToCollection(
$collection
);
This basically filters out products which are “Disabled”. Only “Enabled” products remain in the collection.
Add Product Price To Collection
$collection
= Mage::getResourceModel(
'catalog/product_collection'
);
$collection
->addMinimalPrice()
->addFinalPrice()
->addTaxPercents();
This adds the product prices, i.e base price, final price etc to the collection. Also, price after tax, if applicable.
Filter By Ids
$collection
= Mage::getResourceModel(
'catalog/product_collection'
);
$collection
->addIdFilter(
array
(1,2,3));
//$collection->addIdFilter(array(1,2,3),false);
This puts an id filter, only product with ids 1,2,3 remain in the collection. The function parameter is true/false, this means include/exclude products from collection.
Add Website ID to the collection
$collection
= Mage::getResourceModel(
'catalog/product_collection'
);
$collection
->addWebsiteNamesToResult();