Get entityManager inside an Entity

前端 未结 5 599
自闭症患者
自闭症患者 2020-11-30 09:44

I\'d like to use, something like:

$em = $this->getEntityManager();

Inside a Entity.

I understand I should do this as a s

5条回答
  •  不知归路
    2020-11-30 10:16

    What I think you should do is, instead of using the Entity Manager inside your entity, is to create a custom repository for your entity.

    In your entity ORM file, add an entry as follows (or in your entity class annotations if not using YML):

    App\Bundle\Profils: 
    # Replace the above as appropiate
        type: entity
        table: (your table)
        ....
        repositoryClass: App\Bundle\CustomRepos\ProfilsRepository
        # Replace the above as appropiate. 
        # I always put my custom repos in a common folder, 
        # such as CustomRepos
    

    Now, create a new PHP class that has the namespace above:

    //Your ProfilsRepository.php
    getEntityManager();
           $qb = $em->createQueryBuilder();
           $qb->select... (your logic to retrieve the profil object);
    
           $query = $qb->getQuery();
           $result = $query->getResult();
    
           return $result;
        }
    }
    

    Finally, in your Controller:

    // Your controller
    ;
       ...
       use App\Bundle\CustomRepos\ProfilsRepository;
       use Symfony\Bundle\FrameworkBundle\Controller\Controller;
       ...
       class YourClassNameController extends Controller
       {
          public function yourAction()
          {
             $userId = ;
             // Pass the name of your entity manager to the 
             // getManager function if you have more than one and
             // didn't define any default
             $em = $this->getDoctrine()->getManager();
             $repo = $em->getRepository('Profils');
             $avatar = $repo->getUserProfile($userId);
             ...
    
          }
       }
    

提交回复
热议问题