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

2022-08-30 17:03:53

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

}

不起作用 请帮忙。谢谢


答案 1

您可以通过调用 Doctrine\ORM\EntityRepository#getEntityManager()来访问:EntityManager

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

答案 2

如果您希望更多注入依赖项,请将存储库声明为服务,以便可以注入一个存储库以在另一个存储库中使用它:

服务.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)。


推荐