views:

229

answers:

2

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!

A: 

I did't get remove the null entries section, I think it will produce: tasks.due_date IS NULL AND tasks.due_date IS NULL.

Anyway, maybe you can use Criteria::CUSTOM to write raw-SQL WHERE clause? Example from Propel documentation:

$con = Propel::getConnection(ReviewPeer::DATABASE_NAME);

$c = new Criteria();
$c->add(ReviewPeer::REVIEW_DATE, 'to_date('.ReviewPeer::REVIEW_DATE.', \'YYYY-MM-DD\') = '.$con->quote($date->format('Y-m-d'), Criteria::CUSTOM);
zergu
Thanks for your answer. Unfortunately, custom SQL is not possible with what I am doing as this is part of a larger query.
Jon Winstanley
+2  A: 

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.

Jan Fabry
Ok - I probably just need to upgrade to Propel 1.4 don't I! Thanks for your answer.
Jon Winstanley
I re-tested this in Propel 1.2 and 1.3, and I get the same results. So while you can upgrade (maybe choose 1.5 now, it is stable and much nicer for query building), you don't have to.
Jan Fabry
Fantastic. Thanks for going back and testing that for me. I won't have chance to look at this issue again until this evening.
Jon Winstanley