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

Mil*_* M. 22 php repository symfony doctrine-orm

我需要来自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);
    }

}
Run Code Online (Sandbox Code Playgroud)

不起作用请帮忙.谢谢

Sgo*_*kes 40

您可以通过以下EntityManager方式访问Doctrine\ORM\EntityRepository#getEntityManager():

$repository = $this
    ->getEntityManager()
    ->getRepository('PondGeolocBundle:User_Lake');
Run Code Online (Sandbox Code Playgroud)

  • @DonCallisto`getEntityManager`是一个学说方法,与Symfony2无关.symfony2是否自动设置自定义存储库? (7认同)
  • 既然你没有在你的答案中指明它(并且OP没有对它进行spicify),我想告诉你,因为symfony2.2` - > getEntityManager()`已被弃用,并且使用symfony3,它将被删除.如果你已经有了symfony2.2,请使用` - > getManager()` (3认同)