trante
trante

Reputation: 34006

CakePHP model SQL queries conditions parameter

I have a long query like this:

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

user_type column can take values of 0 or 1. I have a function parameter $type, regarding to this parameter, I need to change my SQL query. Regarding to $type I will query for

I don't want to write same query three times. I want to change only conditions part. Is it possible?

Upvotes: 0

Views: 984

Answers (2)

Choma
Choma

Reputation: 708

Try this:

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

then, in your conditions:

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

given that user_type can take only two values, your third query ("mytable.user_type"=1 OR "mytable.user_type=0) is unnecessary

EDIT :

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

then, for your conditions:

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

Upvotes: 1

Moyed Ansari
Moyed Ansari

Reputation: 8461

you can define $type as an array and manage the values in $type

Like for multiple values

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

for single value

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

Hence you just need to manipulate $type as per condition, Hope this work

Upvotes: 2

Related Questions