yAnTar
yAnTar

Reputation: 4610

Multiple call where in Yii Query builder

I want to build query with multiple call where, but i have error, when use this code

$command = Yii::app()->db->createCommand()
    ->select('*')
    ->from('{{table}}');

$command->where('value1 = :value1', array(':value1' => 1));
$command->where('value2 < :value2', array(':value2' => 2));

I understand, that i can use code like

$command->where('value1 = :value1 AND value2 = :value2', array(':value1' => 1, ':value2' => 2));

but i have difficult conditions and simpler its use code like upper.

In Codeigniter i can use those condition several times

$this->db->where()

Upvotes: 4

Views: 4439

Answers (2)

Karim Samir
Karim Samir

Reputation: 1538

actually I found a better way to do this

$result = array();
    $result = Yii::app()->db->createCommand()
            ->select('*')
            ->from('table');

    $condition = array();
    $cond_arg = array();

    if (!empty($email)) {

        $condition[] = "email =:email";
        $cond_arg[':email'] = $email;
    }

    if (!empty($value2)) {

        $condition[] = "value2 =:value2";
        $cond_arg[':value2'] = $value2;
    }

    if (!empty($value3)) {

        $condition[] = "value3 like :value3";
        $cond_arg[':value3'] = $value3;
    }


    if (count($condition) > 0) {
        $result->where(array('AND', implode(" AND ", $condition)), $cond_arg);
    }

    return $result->queryAll();

Upvotes: 0

Ansari
Ansari

Reputation: 8218

You have to pass it an array like this:

$command->where(array('AND', 'value1 = :value1', 'value2 < :value2'), array(':value1' => 1, ':value2' => 2));

Upvotes: 6

Related Questions