如何在Doctrine 2/Symfony 2中的存储库中获取外部存储库?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (19)

我需要两个不同实体的值。我不知道该怎么做。我已经试过了:

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

}

提问于
用户回答回答于
用户回答回答于

如果你希望注入更多的依赖项,那么将你的存储库声明为服务,这样就可以在另一个库中注入一个来使用它:

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)。

扫码关注云+社区