CakePHP模型SQL查询条件参数


CakePHP model SQL queries conditions parameter

我有一个像这样的长查询:

$a=$this->Signin->find('all',
    array(
        'fields'=> array(
            .....
        ),
        'conditions' => array('mytable.user_type ...),
        'order' => ....
        'limit' => ....
));

user_type列的值可以为0或1。我有一个函数参数$type,关于这个参数,我需要更改我的SQL查询。关于$type,我将查询

  • "mytable.user_type"=1
  • "mytable.user_type"=0
  • "mytable.user_type"=1或"mytable.user_type=0

我不想把同一个查询写三次。我只想更改条件部分。有可能吗?

您可以将$type定义为数组,并管理$type 中的值

类似于多值

$type = array(1,0);
'conditions' => array('mytable.user_type'=>$type)

对于单值

$type = array(1);
'conditions' => array('mytable.user_type'=>$type)

因此,您只需要根据条件操作$type,希望这能起到

的作用

试试这个:

$user_type = ($type == 'something') ? 1 : 0 ;

然后,在你的条件下:

'conditions' => array('mytable.user_type' => $user_type);

假设user_type只能取两个值,则第三个查询("mytable.user_type"=1 OR "mytable.user_type=0)是不必要的

编辑:

if($type == 'conditions_where_usertype_is_necessary') $user_type = ($type == 'something') ? 1 : 0 ;

然后,根据您的情况:

if( isset($user_type) ) {
    $options['conditions']['mytable.user_type'] = $user_type;
}
$options['conditions']['other_conditions'] = ...;
$this->Signin->find('all', $options);