Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 & Doctrine: Create custom SQL-Query

Tags:

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.

like image 985
a1337q Avatar asked Oct 12 '12 15:10

a1337q


People also ask

What is Symfony used for?

Symfony is a feature-rich back-end framework that is used to build complex applications. Many developers still prefer the lightweight Silex micro-framework or the Symfony MicroKernel, and Symfony is a widely used application framework among open-source developers.

Which is better Symfony or Laravel?

There's no clear winner between Laravel and Symfony, as everything depends on your final goal. Laravel is a better choice if: This is your first experience with the framework, as it's easy to learn and has a simpler syntax and better learning materials.

What is Symphony software?

Symfony is an open-source PHP web application framework, designed for developers who need a simple and elegant toolkit to create full-featured web applications. Symfony is sponsored by SensioLabs. It was developed by Fabien Potencier in 2005.

Who created Symfony?

Symfony, powered by SensioLabs, was founded by Fabien Potencier in late 2004 to create websites faster. Shortly after its creation, he decided to release the software under the MIT license. Currently, it is one of the most popular PHP frameworks.


1 Answers

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

like image 151
Thomas Kelley Avatar answered Oct 31 '22 19:10

Thomas Kelley