a1337q a1337q - 3 months ago 37
PHP Question

Symfony2 & Doctrine: Create custom SQL-Query

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



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);
$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: http://doctrine-dbal.readthedocs.org/en/latest/reference/data-retrieval-and-manipulation.html