Search code examples
symfony1propeldate-range

Selecting a date range where date is not null with Propel


Using Propel I would like to find records which have a date field which is not null and also between a specific range.

N.B. Unfortunately, as this is part of a larger query, I cannot utilise a custom SQL query here.

For example: I may have records like this:

---------------------
| ID | DUE_DATE     |
---------------------
| 1  |  NULL        |
| 2  |  01/01/2010  |
| 3  |  02/01/2010  |
| 4  |  NULL        |
| 5  |  05/01/2010  |
---------------------

I may want to return all the rows with a due_date between 01/01/2010 and 02/01/2010 but I don't want to return those records where due_date is NULL.

In the example I only want to return rows 2 and 3.

However, Propel seems to overwrite my NOTNULL criteria.

Is it possible to do this with Propel?

Thanks!


Solution

  • Why do you create the separate Criterion objects?

    $start_date = mktime(0, 0, 0, date("m")  , date("d")+$start, date("Y"));
    $end_date = mktime(0, 0, 0, date("m")  , date("d")+$end, date("Y"));
    
    $c = new Criteria();
    $c->add(TaskPeer::DUE_DATE, $end_date, Criteria::LESS_EQUAL);
    $c->addAnd(TaskPeer::DUE_DATE, $start_date, Criteria::GREATER_EQUAL);
    $c->addAnd(TaskPeer::DUE_DATE, null, Criteria::ISNOTNULL);
    

    When I try this in Propel 1.2, 1.3 or 1.4, I get the following SQL statement:

    SELECT task.TASK_ID, task.DUE_DATE FROM task WHERE ((task.DUE_DATE<=:p1 AND task.DUE_DATE>=:p2) AND task.DUE_DATE IS NOT NULL )

    The $c->add() method replaces the current criterion for the given field. You create your Criterions for TaskPeer::DUE_DATE, so they will always replace the previous ones.