Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP find condition for a query between two dates

I have a start and an end date in my database and a $date variable from a form field. I am now trying to query all the rows where $date is either = start/end date in the db, or ANY date between those two.

It's kind of the opposite of what is described in the docs of how daysAsSql works. I can't figure out how to get it to work. The following line does not work as a find condition in the controller:

'? BETWEEN ? AND ?' => array($date, 'Item.date_start', 'Item.date_end'),

Any help is greatly appreciated. This is driving me crazy.

Here is the complete Query and corresponding SQL:

$conditions = array(
            'conditions' => array(
            'and' => array(
                '? BETWEEN ? AND ?' => array($date, 'Item.date_start', 'Item.date_end'),
                'Item.title LIKE' => "%$title%",
                'Item.status_id =' => '1'
                )));

        $this->set('items', $this->Item->find('all', $conditions));



WHERE (('2012-10-06' BETWEEN 'Item.date_start' AND 'Item.date_end') AND (`Item`.`title` LIKE '%%') AND (`Item`.`status_id` = 1))
like image 815
Joshua Avatar asked Aug 13 '12 09:08

Joshua


2 Answers

$conditions = array(
        'conditions' => array(
        'and' => array(
                        array('Item.date_start <= ' => $date,
                              'Item.date_end >= ' => $date
                             ),
            'Item.title LIKE' => "%$title%",
            'Item.status_id =' => '1'
            )));

Try the above code and ask if it not worked for you.

Edit: As per @Aryan request, if we have to find users registered between 1 month:

$start_date = '2013-05-26'; //should be in YYYY-MM-DD format
$this->User->find('all', array('conditions' => array('User.reg_date BETWEEN '.$start_date.' AND DATE_ADD('.$start_date.', INTERVAL 30 DAY)')));
like image 82
Arun Jain Avatar answered Nov 15 '22 19:11

Arun Jain


Here is CakePHP BETWEEN query example.

I'm defining my arrays as variables, and then using those variables in my CakePHP find function call:

// just return these two fields
$fields = array('uri', 'page_views');

// use this "between" range
$conditions = array('Event.date BETWEEN ? and ?' => array($start_date, $end_date));

// run the "select between" query
$results = $this->Event->find('all', 
         array('fields'=>$fields, 
               'conditions'=>$conditions));

Ref from

like image 39
Aditya P Bhatt Avatar answered Nov 15 '22 21:11

Aditya P Bhatt