Multiple call where in Yii Query builder

匆匆过客 提交于 2019-12-10 16:26:34

问题


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()

回答1:


You have to pass it an array like this:

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



回答2:


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();


来源:https://stackoverflow.com/questions/11562823/multiple-call-where-in-yii-query-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!