Karishma Sharma
Karishma Sharma

Reputation: 7

Add attribute to filter AND condition magento

I m trying to filter out the collection by name which can start from a,b,c and d alphabets.

I have tried following codes

1) addFieldToFilter( 'm_name',array('like' => 'a%'), 'm_name',array('like' => 'b%'), 'm_name',array('like' => 'c%') )

2) addFieldToFilter(array( array('m_name','like' => 'a%'), array('m_name','like' => 'b%'), array('m_name','like' => 'c%'), ))

But both of these are displaying the collection of names starting with alphabet 'a' only.(not b,c,and d). Please help me for getting the right collection.

I have also tried this code $collection = Mage::getModel('manufacturers/manufacturers')->getCollection() ->addStoreFilter(Mage::app()->getStore(true)->getId()) ->addFieldToFilter('m_name',array(array('like'=>'a'.'%')) , array('like'=>'b'.'%'),array('like'=>'c'.'%')) ->addFieldToSelect('*')->load();

But still it is displaying collection of names starting with alphabet 'a' only

Upvotes: 0

Views: 3176

Answers (2)

Jürgen Thelen
Jürgen Thelen

Reputation: 12727

You're not searching for AND, but for OR.

If you AND a LIKE a% and a LIKE b% you'll always get an empty result. That's because the same attribute value can only start with a OR b, but never with a AND b.

To define an OR filter for a specific attribute you can use a single addFieldToFilter() call and pass an array of arrays to it:

$collection = Mage::getModel('catalog/product')->getCollection()
    ->addFieldToFilter(
        'm_name',
        array(
            array(
                'like' => 'a%'
            ),
            array(
                'like' => 'b%'
            )
        )
    );

Upvotes: 1

Vishal
Vishal

Reputation: 900

Hello check below code may be help you

$collection = Mage::getModel('catalog/product')->getCollection()
          ->addAttributeToSort('name', 'asc')
          ->addFieldToFilter('name',array(array('like'=>'a%'), array('like'=>'b%'), array('like'=>'c%'), array('like'=>'d%')))
              ->addAttributeToSelect('*');
foreach ($collection as $product) {
      echo $product->getName() . "<br />";
}

Upvotes: 0

Related Questions