在条令实体内部执行自定义查询


Performing a custom query inside Doctrine entity

我有一个负责管理自定义模板的实体(B)。在更新实体A时,我需要查询实体B以获取所需的模板并进行必要的处理。

类似于:

use Doctrine'ORM'Mapping as ORM;
use Doctrine'ORM'EntityRepository;
use Bundle'EmailsBundle'Entity'Email;
use Symfony'Component'Validator'ExecutionContextInterface;
class MemberApplication extends EntityRepository
{
    public function sendUpdateNotificationEmails()
    {
        // Send email to user
        $emailRow = $this->getEntityManager()
            ->createQuery("SELECT * FROM emails where `type` = 'x' LIMIT 1")
            ->getResult();        
    }

    (...)
}

这给我返回了一个错误:

Fatal error: Call to a member function createQuery() on a non-object in Classpath/Classname.php

$this->getEntityManager()和$this-->_em都为NULL。

我在http://symfony.com/doc/current/book/doctrine.html#custom-存储库类,我无法理解为什么这不起作用。

感谢

this->getEntityManager()返回null,因为没有注入对条令的依赖。尝试$this->getDoctrine()->getEntityManager();相反这应该在控制器端完成,所以类似这样的事情:

$em = $this->getDoctrine()->getManager();
$memberRepo = $em->getRepository('MyBundle:MemberApplication');
$result = $memberRepo->sendUpdateNotificationEmails();

那么在您的函数中,您应该返回$emailRow或您想要的内容。