How to get foreign repository inside my repository in Doctrine2/Symfony2?

那年仲夏 提交于 2019-12-03 14:56:40

问题


I need values from 2 different entities. I don't know how to do. I tried this so far:

<?php

namespace Pond\GeolocBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * PondLakeRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class PondLakeRepository extends EntityRepository
{

    public function getSwimsAvailableById($id)
    {
        // get the nb of swims of a lake
        $lake = $this->findOneById($id);
        $swims = $lake->getSwims();

        $repository = $this->getDoctrine()
                           ->getManager()
                           ->getRepository('PondGeolocBundle:User_Lake');

        //get the nb of users in a lake
        $qb = $this->_em->createQueryBuilder();
        $qb->select('count(a.id)');
        $qb->from('PondGeolocBundle:User_Lake', 'a');

        $nbOfUsers = $qb->getQuery()->getSingleScalarResult();

        // return the nb of swims available onthis lake
        $avail = $swims - $nbOfUsers;
        print_r ($avail);
    }

}

Doesn't work Please help. Thanks


回答1:


You can access the EntityManager by calling Doctrine\ORM\EntityRepository#getEntityManager():

$repository = $this
    ->getEntityManager()
    ->getRepository('PondGeolocBundle:User_Lake');



回答2:


If you like more to inject dependencies, declare your repositories as services so you can inject one to use it inside the other:

services.yml

services:
    repository.user_lake:
        class: Pond\GeolocBundle\Entity\UserLakeRepository
        factory: [@doctrine, getRepository]
        arguments:
            - PondGeolocBundle:User_Lake

    repository.pond_lake:
        class: Pond\GeolocBundle\Entity\PondLakeRepository
        factory: [@doctrine, getRepository]
        arguments:
            - PondGeolocBundle:PondLake
        calls:
            - [setUserLakeRepository, [@repository.user_lake]]

in PondLakeRepository.php you must have a setter (setUserLakeRepository) to a property to store the repository (i.e. $userLakeRepository).



来源:https://stackoverflow.com/questions/15466513/how-to-get-foreign-repository-inside-my-repository-in-doctrine2-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!