【发布时间】:2012-10-03 11:09:52
【问题描述】:
如何使用 Doctrine 在 Symfony2 中创建自定义 SQL 查询?或者没有教义,我不在乎。
不能这样工作:
$em = $this->getDoctrine()->getEntityManager();
$em->createQuery($sql);
$em->execute();
谢谢。
【问题讨论】:
如何使用 Doctrine 在 Symfony2 中创建自定义 SQL 查询?或者没有教义,我不在乎。
不能这样工作:
$em = $this->getDoctrine()->getEntityManager();
$em->createQuery($sql);
$em->execute();
谢谢。
【问题讨论】:
您可以直接从实体管理器中获取 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 几乎可以处理您可能需要的任何查询。
【讨论】:
你可以执行这段代码,它可以工作:
$em = $this->getDoctrine()->getEntityManager();
$result= $em->createQuery($sql)->getResult();
【讨论】:
$em->createQuery() 不执行 SQL,而是执行 DQL。