php Symfony2 和 Doctrine:创建自定义 SQL 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12862389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:23:04  来源:igfitidea点击:

Symfony2 & Doctrine: Create custom SQL-Query

phpsqlsymfonydoctrine

提问by a1337q

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

如何使用 Doctrine 在 Symfony2 中创建自定义 SQL 查询?或者没有教义,我不在乎。

Doesn't work like this:

不是这样工作的:

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

Thanks.

谢谢。

回答by Thomas Kelley

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

回答by Yassine EL MALKI

You can execute this code it works :

您可以执行此代码,它可以工作:

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