How to use Raw SQL Queries in Symfony 2

hashtag-doctrine-dogSometimes, usually when you first start with Symfony 2 (but there are other times too), you just want to get access to good old raw SQL.

I have experimented with a few different ways, and – as with many Symfony issues – the documentation is either shonky, or worst, so cryptic it requires a Mensa-like IQ level to decode just WTF these guys are talking about.

Now, if you are new to Symfony 2, before you go about using raw SQL for everything, do yourself a favour and make sure you learn Doctrine.

And then only if you absolutely must go native SQL, then use the following:

    public function foobar($foobar)
      $stmt = $this->getEntityManager()
                   ->prepare('SELECT COUNT(id) AS num, foo FROM bar WHERE foobar = :foobar GROUP BY foo');
      $stmt->bindValue('foobar', $foobar);
      return $stmt->fetchAll();

I love this, and I have used it with great success!, but the credit is not mine, it belongs to a user called althaus on the old symfony forums.

Be Sociable, Share!

2 thoughts on “How to use Raw SQL Queries in Symfony 2”

  1. “Mensa-like IQ” – I beg to differ. I look like 15 seconds at a 50 line query and if I do not *instantly* understand what it means then it is garbage! Same with fancy-framework-I-don’t-even-care-which-one: I look like 15 seconds at the documentation and if it doesn’t even fit on the screen then I suppose someone failed to be concise AND intelligent enough. You can talk all day long as fancy as you want and it is still the content that is important. This has been so multiples of thousands of years and it will never change, no matter what language you use or who you are.

Leave a Reply

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

This blog is kept spam free by WP-SpamFree.