Reputation: 10536
I've a method that returns a Doctrine_Collection, with a whereIn()
clause :
public function getByValues($values)
{
if (!is_array($values))
throw new sfException('Wrong parameter type. Excepted array.');
return Doctrine_Query::create()
->from('Anomaly a')
->whereIn('a.value', $values);
}
However, when $values
is an empty array, this method return all the rows that are in the AnomalyTable. This isn't an unexpected behavior, as documented in Doctrine documentation, and written here : Doctrine where in with Doctrine_Query
However, I would like to return an empty Doctrine_Collection
instead of the result of my query, when $values
is an empty array.
Any ideas on how I can do that ?
Thanks =)
Adding an impossible clause, like ->where('1=0')
would do the trick, but it is an unnecessary request to the DB server. Does anyone have a better idea ?
Upvotes: 3
Views: 3337
Reputation: 132
And what about (you need also the execute method to get the result of the query ! with that the return type will be the same everytime) :
public function getByValues($values)
{
if (!is_array($values))
throw new sfException('Wrong parameter type. Excepted array.');
if (empty($values)) {
return new Doctrine_Collection('Anomaly');
}
return Doctrine_Query::create()
->from('Anomaly a')
->whereIn('a.value', $values)
->execute()
;
}
Upvotes: 4
Reputation: 11411
I personnaly use the following trick:
public function getByValues($values)
{
if (!is_array($values))
throw new sfException('Wrong parameter type. Excepted array.');
$values = empty($values) ? array(-1) : $values;
return Doctrine_Query::create()
->from('Anomaly a')
->whereIn('a.value', $values);
}
Works great even if somewhat hackish.
Upvotes: 1
Reputation: 4506
I think it's impossible to do that. The Doctrine_Collection is more than a resultset/array of objects. It also has means of deleting and adding objects and keeping that state.
That's probably also why many native Doctrine functions return FALSE
when no results were found. (For instance, the NestedSet functions).
So, for you it's probably best to return FALSE as well. or maybe an empty array. Both arrays as Doctrine_Collection can be used in a foreach
loop and count
function.
Should you want to use the delete
and add
functions, you could just call the constructor.
Upvotes: 1
Reputation: 58619
if(count($values)){
return Doctrine_Query::create()
->from('Anomaly a')
->whereIn('a.value', $values);
} else {
return Doctine_Query::create()
->from('Anomaly a')
->where('0=1');
}
Upvotes: 1
Reputation: 15378
By value, I assume you mean $values
right? just add something to check if values is empty and then manually supply an empty collection.
if(empty($values))
return Doctine_Query::create()->from('Anomaly a')->where('1=0');
Upvotes: 1