john smith
john smith

Reputation: 185

Filtering on date range in CakePHP controller

I have a Subtask and a Horse model.

Horse hasMany Subtask.

Subtask has a date associated with it. It is a MYSQL date object, NOT a datetime.

In my View/Horse/view.ctp, I want to only print out subtasks that are between a given date range, and I am having difficulty doing that. I can pass in subtasks using regular filtering, in my controller method:

    $this->set('incomplete_subtasks', $this->Subtask->find('all', array('conditions' => array(
                'and' => array(
                    'completed ' => 0,
                    'Subtask.horse_id ' => $id)))));

I am trying to filter on a date range using this:

$this->set('incomplete_subtasks', $this->Subtask->find('all', array('conditions' => array(
                'and' => array(
                    'completed ' => 0,
                    'Subtask.horse_id ' => $id,
                    'Subtask.date BETWEEN ? AND ?' => array(
                    date(Y-m-d),
                    date(Y-m-d, strtotime('+1 week'))

                    )
                )
            )
            )));

I get this error in horse/view:

Notice (8): Use of undefined constant Y - assumed 'Y' [APP/Controller/HorsesController.php, line 56]

I get that error for every constant I am using in the expression- there are six of them total.

Upvotes: 1

Views: 2106

Answers (1)

scrowler
scrowler

Reputation: 24406

I'm not sure what you mean by "constant" as I can't see any constants in your code, I'm guessing it's because you haven't wrapped Y-m-d in quotes (so PHP assumes they are constants).

Firstly, try wrapping them in quotes:

'Subtask.date BETWEEN ? AND ?' => array(
    date('Y-m-d'),
    date('Y-m-d', strtotime('+1 week'))
)

Failing that, you should do a simple <= and >= for your dates instead, and the and key of your conditions isn't necessary here (unless there are other array keys you're omitting in your code).

Try this:

$this->set('incomplete_subtasks', $this->Subtask->find('all', array('conditions' => 
    array(
        'completed ' => 0,
        'Subtask.horse_id ' => $id,
        'Subtask.date >=' => date('Y-m-d'),
        'Subtask.date <=' => date('Y-m-d', strtotime('+1 week'))
    )
)));

Upvotes: 1

Related Questions