Search code examples
phpsearchyiisql-likecriteria

I'm using Yii addColumnCondition and want to change the default behaviour from '=' to using LIKE and %


I'm using the addColumnCondition function as I like how it forms the queries for multiple queries. But I can't find anything in the documentation to change it's comparison operation from the simple = needle to a LIKE %needle%. There is a function that does a LIKE in addSearchCondition() but then it means to get the same query formation result, I'll have to do some for loops and merge conditions which I'd like to avoid if there is a better solution.

Here's the code

foreach($query_set as $query){
    foreach($attributes as $attribute=>$v){
        $attributes[$attribute] = $query;
    }
    $criteria->addColumnCondition($attributes, 'OR', 'AND');
}

And I'm getting the condition formed like

(business_name=:ycp0 OR payment_method=:ycp1) AND (business_name=:ycp2 OR payment_method=:ycp3)

So is there a way to configure the function to use LIKE %:ycp0% instead of the simple =:ycp0.


Solution

  • It seems, this feature is not provided by Yii's addColumnCondition method.

    therefore i would recommend a way of overriding the method of CDbCriteria class and customize it your own way.

    you need to create a new class called "AppCriteria", then place it inside protected/models

    The code for the new class should look like,

    i.e

    class AppCriteria extends CDbCriteria {
    
       public function addColumnCondition($columns, $columnOperator = 'AND', $operator = 'AND', $like = true) {
          $params = array();
          foreach ($columns as $name=>$value) {
             if ($value === null)
                $params[] = $name.' IS NULL';
             else {
                if ($like)
                   $params[] = $name.' LIKE %'.self::PARAM_PREFIX.self::$paramCount.'%';
                else
                   $params[] = $name.'='.self::PARAM_PREFIX.self::$paramCount;
                $this->params[self::PARAM_PREFIX.self::$paramCount++] = $value;
             }
          }
          return $this->addCondition(implode(" $columnOperator ", $params), $operator);
       }
    }
    

    Note: The 4th param of addColumnCondition, $like = true. you can set it to $like = false and allow the function to work with equal conditions. (A = B)

    i.e

    (business_name=:ycp0 OR payment_method=:ycp1) AND (business_name=:ycp2 OR payment_method=:ycp3)
    

    if $like = true, it will allow you to have like condition. (A like %B%)

    i.e

    (business_name LIKE %:ycp0% OR payment_method LIKE %:ycp1%) AND (business_name LIKE %:ycp2% OR payment_method LIKE %:ycp3%)
    

    Now Here's the working code,

    $criteria = new AppCriteria();
    foreach($query_set as $query){
        foreach($attributes as $attribute=>$v){
            $attributes[$attribute] = $query;
        }
        $criteria->addColumnCondition($attributes, 'OR', 'AND');
    }