我正在尝试使用Doctrine将原始查询执行到Symfony框架中。
这里有代码:
class MessagesHandler
{
/** @var \Doctrine\Common\Persistence\ObjectManager The entity manager used to access entities */
protected $em = null;
public function __construct($em)
{
$this->em = $em;
}
public function getMessagesToPost($user)
{
$query = 'SELECT COUNT(*) FROM `messages` WHERE `posted_by` = ' . $user->getId() . ' AND `message_posted` = 0';
return $this->em->getConnection()->exec($query);
}
我已将MessagesHandler类设置为服务:
services:
shq.handler.Messages:
class: AppBundle\Handler\MessagesHandler
arguments: ["@doctrine.orm.entity_manager"]
现在,当我执行代码时,收到以下错误:
SQLSTATE [HY000]:常规错误:2014无法执行查询 其他未缓冲的查询处于活动状态。考虑使用 PDOStatement对象::使用fetchall()。或者,如果您的代码只是永远 要对mysql运行,您可以通过设置启用查询缓冲 PDO :: MYSQL_ATTR_USE_BUFFERED_QUERY属性。“)...
如何使用PDOStatement::fetchAll()
?
答案 0 :(得分:0)
使用createNativeQuery
方法:
$query = $entityManager->createNativeQuery('SELECT COUNT(*) FROM `messages` WHERE `posted_by` = ? AND `message_posted` = 0', $rsm);
$query->setParameter(1, $user->getId());
$count = $query->getResult();
此处提供的文档:http://doctrine-orm.readthedocs.org/en/latest/reference/native-sql.html
答案 1 :(得分:0)
由于建议的解决方案对我来说太复杂了,我继续寻找更简单的解决方案,我想出了这个:
public function getMessagesToPost($user)
{
$query = 'SELECT COUNT(*) FROM `messages` WHERE `posted_by` = :userId AND `message_posted` = 0';
$params = array(
'userId' => $user->getId()
);
/** @var \Doctrine\DBAL\Statement $preparedQuery */
$preparedQuery = $this->em->getConnection()->prepare($query);
$preparedQuery->execute($params);
$result = $preparedQuery->fetch();
// Return the first value of the returned array
return array_shift($result);
}
灵感形式here。