2

I would like to use entity manager inside entity and no idea for usage.

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;
      }  
}

Using this code get me error

     Call to a member function getRepository() on null"

The entity manager is null also

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

Any idea for example usage?

ira
  • 534
  • 1
  • 5
  • 17
  • 1
    I don't know about the usage of `ObjectManagerAware` but having Object Manager oin Entity is quite bad. The question may be a duplicate of https://stackoverflow.com/questions/14684745/get-entitymanager-inside-an-entity too. – Etshy Mar 29 '19 at 10:12

1 Answers1

0

You can try to create a repository like here. Just add

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

or to YAML, Xml depends on your configuration and then create the repository file. Like this one:

// 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();
  }
}
Oscar
  • 1,929
  • 3
  • 16
  • 31