【问题标题】:Example Usage of ObjectManagerAware inside entity实体内部 ObjectManagerAware 的示例用法
【发布时间】:2019-03-29 00:51:20
【问题描述】:

我想在实体内部使用实体管理器,但不知道如何使用。

use Doctrine\Common\Persistence\ObjectManagerAware;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;

use SomeBundle\Entity\Boarding;
use SomeBundle\Entity\User;


class Entity extends ApiUserEntity implements ObjectManagerAware
{
     private $em;
     public function ___construct(User $user)
     {
         $this->board = $this->getData(123);
     }
     public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata)
     {
           $this->em = $objectManager;

     }
     private function getData($leadId)
     {
          //return gettype($this->em); //return null
            $repository =$this->em->getRepository(Boarding::class);
            $query = $repository->createQueryBuilder('b')
               ->where('b.lead = :lead')
               ->setParameter('lead', $leadId)
               ->getQuery();
             $boards = $query->getResult();
             return $boards;
      }  
}

使用此代码会出错

     Call to a member function getRepository() on null"

实体管理器也为空

      //return gettype($this->em); //return null

任何想法例如用法?

【问题讨论】:

标签: symfony doctrine


【解决方案1】:

您可以尝试创建类似here 的存储库。只需添加

 * @ORM\Entity(repositoryClass="App\Repository\EntityRepository")

或者对于 YAML,Xml 取决于你的配置然后创建存储库文件。喜欢这个:

// src/AppBundle/Repository/ProductRepository.php
namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

class ProductRepository extends EntityRepository
{
  public function findAllOrderedByName()
  {
      return $this->getEntityManager()
          ->createQuery(
            'SELECT p FROM AppBundle:Product p ORDER BY p.name ASC'
          )
          ->getResult();
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    相关资源
    最近更新 更多