Snippets with the tag: collection

Get attribute set collection

Description

get the entity attribute set collection

Code

$attributeSetCollection = Mage::getResourceModel('eav/entity_attribute_set_collection') ->load();

Get all top level categories

Description

Get all of the top level categories. Usually, the first base category added will have the id of 2.

Code

$defaultCategoryId = 2; 
$topLevelCats = Mage::getModel('catalog/category') 
->getCollection() 
->addAttributeToSelect('path','name','id') 
->addAttributeToFilter('parent_id', $defaultCategoryId) 
->setOrder('position', 'ASC');

Print the SQL queries performed when calling a product collection

Description

Print the SQL queries performed when calling a product collection

Code

$_productCollection->printLogQuery(true);

Load products by category ID

Description

Load products by category ID, for example 12.

Code

$_category = Mage::getModel('catalog/category')->load(12);
$_productCollection = $_category->getProductCollection();
if($_productCollection->count()) {
    foreach( $_productCollection as $_product ):
        echo $_product->getProductUrl();
        echo $this->getPriceHtml($_product, true);
        echo $this->htmlEscape($_product->getName());
    endforeach;
}

Get / filter all products by attribute value

Description

Get / filter all products by attribute value

Get all products related to any particular brand. Let us suppose that we are fetching the products related to ‚Apple‘ brand. The manufacturer ID of Apple = 3.

Code

$manufacturerId = 3;
$attributeCode = 'manufacturer';

$products = Mage::getModel('catalog/product')->getCollection()->addAttributeToFilter($attributeCode, $manufacturerId);

// print all products
print_r($products->getItems());

Get a list of bestsellers

Description

Get a list of bestsellers

Code

$collection = Mage::getResourceModel('sales/report_bestsellers_collection')
        ->setModel('catalog/product')
        ->addStoreFilter(Mage::app()->getStore()->getId()) //if you want the bestsellers for a specific store view. if you want global values remove this
    ->setPageSize(5)//set the number of products you want
    ->setCurPage(1);
foreach ($collection as $_product){
    $realProduct = Mage::getModel('catalog/product')->load($_product->getProductId());
    //do something with $realProduct;
}