views:

153

answers:

2

Hi,

Is it possible to craft a wildcard WHERE query with Doctrine, like so:

->where('this_field = ?', ANYTHING);

I'd be using this to build a search query dynamically out of unknown user-selected parameters and therefore would need to have the condition in place but capable of accepting the value "anything".

To add, I can get this to work:

$field = 'this_field = ?';
$value = 5;
...
->where($field, $value);

... but it's still doesn't allow me to use "anything" as value or to eliminate the entire query condition. The following fails:

$field = NULL;
$value = NULL;
...
->where($field, $value);

Thanks

A: 

[Answer to own question]

After playing around with this, found a solution that works, posting here for others.

Using ->whereIn allows Doctrine to ignore a query condition completely:

$empty = array();
...
->andWhereIn('this_field', $empty)

The above condition doesn't get included in the resulting SQL at all.

Tom
+2  A: 

If you build the query dynamically you can also check wther $value has a value or not and then add the where part if necessary. E.g.

$q; // Your query object.

if(isset($value)) {   // or empty() or maybe just if($value) depending on your needs.
    $q->where('this_field = ?', $value);
}

This is easier to understand and easier to debug imo.

Felix Kling
Felix, ah yes indeed, that's the way to do it. Manipulating the query object is the easiest for building it dynamically. Thanks.
Tom