【问题标题】:Symfony2 & Doctrine: Create custom SQL-QuerySymfony2 & Doctrine:创建自定义 SQL 查询
【发布时间】:2012-10-03 11:09:52
【问题描述】:

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

不能这样工作:

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

谢谢。

【问题讨论】:

    标签: php sql symfony doctrine


    【解决方案1】:

    您可以直接从实体管理器中获取 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();
    

    但是,除非真的有必要,否则我建议不要这样做... Doctrine 的 DQL 几乎可以处理您可能需要的任何查询。

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

    【讨论】:

    • Doctrine 中也有 Native SQL 的规定:docs.doctrine-project.org/en/latest/reference/native-sql.html
    • 请注意 getEntityManager 自 Symfony 2.1 起已被弃用。改用 getManager
    • 虽然 Doctrine 和 DQL 以及 querybuilder 确实可以完成您想要对数据库执行的 90% 的操作,但有时您需要运行查询并且您不会听到对象和约束。这通常会在我进行报告时出现。
    【解决方案2】:

    你可以执行这段代码,它可以工作:

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

    【讨论】:

    • $em->createQuery() 不执行 SQL,而是执行 DQL。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多