Symfony2 & Doctrine: Create custom SQL-Query

后端 未结 2 636
野趣味
野趣味 2020-12-05 10:14

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->getD         


        
相关标签:
2条回答
  • 2020-12-05 10:49

    You can execute this code it works :

    $em = $this->getDoctrine()->getEntityManager();
    $result= $em->createQuery($sql)->getResult();
    
    0 讨论(0)
  • 2020-12-05 10:55

    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

    0 讨论(0)
提交回复
热议问题