December 29, 2013

December 29, 2013
1
In Magento, we have a lot of product attributes. It is difficult to fetch the products with a specific attribute. In this article, we are going to discuss about How to fetch the products with specific attribute value in Magento. To fetch the products, we need to instantiate the Product collection.

Use the below code to instantiate the product collection.

$collection = Mage::getModel('catalog/product')->getCollection();

Magento products are EAV style model. So we need to add additional attributes that you want to return. Use the below codes.

$collection = Mage::getModel('catalog/product')->getCollection();
//fetch name and size into data
$collection->addAttributeToSelect('name');
$collection->addAttributeToSelect('size');

We can select the attributes as like the below code.

$collection->addAttributeToSelect('*')

There are multiple syntax for setting filters on collections:

//filter for products whose orig_price is greater than (gt) 100
$collection->addFieldToFilter(array(
        array('attribute'=>'price','gt'=>'100'),
));     

//AND filter for products whose orig_price is greater than (lt) 130
$collection->addFieldToFilter(array(
        array('attribute'=>'price','lt'=>'130'),
));

//filter for products who name is equal (eq) to Widget A, or equal (eq) to Widget B
$collection->addFieldToFilter(array(
array('attribute'=>'name','eq'=>'Widget A'),
array('attribute'=>'name','eq'=>'Widget B'),
));

foreach ($collection as $product)
{
        //var_dump($product);
        var_dump($product->getData());
}

Below are the list of some most used short conditionals:

eq – equal
neq – not equal
like – %like%
nlike – not %like%
in – in(array…)
nin – not in(array…)
notnull
null
moreq – >=
gt – >
lt – <
gteq – >=
lteq – <=

1 comments:

  1. your attempt is very good and i appreciate it,
    can you please tell me how can i implement this on category product pages.
    because i try but no result in catalog product list page.
    any replay is appreciate..:)

    ReplyDelete