24

How can I create a custom SQL query in Symfony2 using Doctrine? Or without Doctrine, I don't care.

Doesn't work like this:

    $em = $this->getDoctrine()->getEntityManager();
    $em->createQuery($sql);
    $em->execute();

Thanks.

Thomas Kelley
  • 10,187
  • 1
  • 36
  • 43
a1337q
  • 770
  • 3
  • 10
  • 20

2 Answers2

82

You can get the Connection object directly from the Entity Manager, and run SQL queries directly through that:

$em = $this->getDoctrine()->getManager(); // ...or getEntityManager() prior to Symfony 2.1
$connection = $em->getConnection();
$statement = $connection->prepare("SELECT something FROM somethingelse WHERE id = :id");
$statement->bindValue('id', 123);
$statement->execute();
$results = $statement->fetchAll();

However, I'd advise against this unless it's really necessary... Doctrine's DQL can handle almost any query you might need.

Official documentation: https://www.doctrine-project.org/projects/doctrine-dbal/en/2.9/reference/data-retrieval-and-manipulation.html

Paulo Lima
  • 65
  • 1
  • 6
Thomas Kelley
  • 10,187
  • 1
  • 36
  • 43
  • 10
    There is also the Native SQL provision in Doctrine: http://docs.doctrine-project.org/en/latest/reference/native-sql.html – Orbling Oct 12 '12 at 15:43
  • 2
    Please note getEntityManager is deprecated since Symfony 2.1. Use getManager instead – Oli Sep 28 '16 at 08:55
  • 2
    While it's true that Doctrine and DQL and querybuilder can probably do 90% of what you want to do with a database, but sometimes you need to run queries and you don't the object overheard and constraints. This usually come up for me when I'm doing reporting. – Halfstop Oct 07 '16 at 19:13
-2

You can execute this code it works :

$em = $this->getDoctrine()->getEntityManager();
$result= $em->createQuery($sql)->getResult();