简体   繁体   English

Symfony2&Doctrine:创建自定义SQL查询

[英]Symfony2 & Doctrine: Create custom SQL-Query

How can I create a custom SQL query in Symfony2 using Doctrine? 如何使用Doctrine在Symfony2中创建自定义SQL查询? Or without Doctrine, I don't care. 或者没有学说,我不在乎。

Doesn't work like this: 不这样工作:

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

Thanks. 谢谢。

You can get the Connection object directly from the Entity Manager, and run SQL queries directly through that: 您可以直接从实体管理器获取Connection对象,并直接通过以下方式运行SQL查询:

$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. 但是,除非确实有必要,否则我建议不要这样做...... Doctrine的DQL几乎可以处理您可能需要的任何查询。

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

You can execute this code it works : 你可以执行它的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM