Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use 'like' instead of '=' in magento collection filter for custom module

i have managed to do this with addFieldToFilter default functionality like this:

$collection->addFieldToFilter(
    array('first_name','last_name'),
    array($post['firstName'],$post['lastName'])             
);

this is working when i print sql (this is just part from the whole statement being printed):

((first_name = 'r') OR (last_name = 't'))

now i am trying to understand how to use 'like' instead of =. need some help in understanding that.

your time and answers are highly appericiated thank you.

like image 939
R T Avatar asked Mar 23 '23 20:03

R T


1 Answers

It's weird, but after some researching into your question the solution is quite simple - it's given in the comments in the Magento code:

In the comment for the method addAttributeToFilter() in Mage/Eav/Model/Entity/Collection/Abstract.php (which finally gets called) you can read:

/**
 * Add attribute filter to collection
 *
 * If $attribute is an array will add OR condition with following format:
 * array(
 *     array('attribute'=>'firstname', 'like'=>'test%'),
 *     array('attribute'=>'lastname', 'like'=>'test%'),
 * )
 */

Wasn't quite clear to me what this was supposed to mean, but it's as simple: If you want to add an OR condition between the attributes in your statement, then you have to give your parameter for the addAttributeToFilter() method in this way, so in your case:

$collection->addFieldToFilter(
array(
   array('attribute'=>'firstname', 'like'=>$post['firstName']),
   array('attribute'=>'lastname', 'like'=>$post['lastName'])
));

You can follow this if you look inside the addAttributeToFilter() method:

if (is_array($attribute)) {
        $sqlArr = array();
        foreach ($attribute as $condition) {
            $sqlArr[] = $this->_getAttributeConditionSql($condition['attribute'], $condition, $joinType);
        }
        $conditionSql = '('.implode(') OR (', $sqlArr).')';
like image 84
peter gunn Avatar answered Apr 26 '23 20:04

peter gunn