Search code examples
phpsymfony1doctrinedqldoctrine-collection

How to return an empty Doctrine_Collection?


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 =)

Edit:

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 ?


Solution

  • 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()
      ;
    }