【问题标题】:Performing a custom query inside Doctrine entity在 Doctrine 实体中执行自定义查询
【发布时间】:2013-12-10 20:11:14
【问题描述】:

我有一个负责管理自定义模板的实体 (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-repository-classes 中读到了类似的方法,但我无法弄清楚为什么这不起作用。

谢谢

【问题讨论】:

  • 您没有加载实体吗?使用 Bundle\Whatever\Entity\EntityName;
  • 我现在。输出仍然是相同的。更新了代码

标签: php symfony doctrine-orm


【解决方案1】:

this->getEntityManager() 返回 null 因为没有注入对学说的依赖。试试 $this->getDoctrine()->getEntityManager();反而。这应该在控制器端完成,但如下所示:

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

那么在你的函数中你应该返回 $emailRow 或者你想要的。

【讨论】:

  • 在控制器上执行此操作的问题是我使用的是 Sonata admin,这会使我重复代码。想避免这种情况,但我想这是正确的做法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多