Symfony Doctrine “where in” and “where not in” Syntax

When you’re utilizing Doctrine to search a database for a value not present in a given set, it might be tempting to use some sloppy code like the following:

$excuse = ExcuseTable::getInstance()
  ->createQuery('e')
  ->where('e.id NOT IN ('.implode(',', $arrayOfAlreadyUsedIds).')')
  ->fetchOne();

While code like this can work, it’s difficult to read and error prone. Just think if the given array has data that needs to be escaped; You’ll have to tack on a call to array map in there too, making your code all the more messy. There’s just no excuse for that kind of thing.

Instead, write cleaner code and let Doctrine do all the hard work for you: (Notice the change on line 3.)

$excuse = ExcuseTable::getInstance()
  ->createQuery('e')
  ->whereNotIn('e.id', $arrayOfAlreadyUsedIds))
  ->fetchOne();

Note: the syntax for ->whereIn works exactly the same way.

This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to Symfony Doctrine “where in” and “where not in” Syntax

  1. Andrey says:

    Thank you for help! :)

  2. Felipe says:

    Thank you for your help!

    Note: There is an extra “)” at the end of the third line.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>