如何在Doctrine2 / Symfony2中的我的存储库中获取外部存储库?

时间:2013-03-17 21:36:23

标签: php symfony doctrine-orm repository

我需要来自2个不同实体的值。我不知道该怎么做。 到目前为止我试过这个:

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

}

不起作用 请帮忙。 感谢

2 个答案:

答案 0 :(得分:38)

您可以致电Doctrine\ORM\EntityRepository#getEntityManager()

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

答案 1 :(得分:0)

如果您想要更多注入依赖项,请将您的存储库声明为服务,这样您就可以注入一个以在另一个中使用它:

<强> 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]]
在PondLakeRepository.php中,你必须有一个setter(setUserLakeRepository)来存放一个存储库(即$ userLakeRepository)。