25

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

}

不起作用请帮助。谢谢

4

2 回答 2

49

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

$repository = $this
    ->getEntityManager()
    ->getRepository('PondGeolocBundle:User_Lake');
于 2013-03-17T22:57:56.930 回答
0

如果您更喜欢注入依赖项,请将您的存储库声明为服务,以便您可以注入一个以在另一个内部使用它:

服务.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 中,您必须有一个属性设置器 (setUserLakeRepository) 来存储存储库(即 $userLakeRepository)。

于 2017-02-08T15:39:18.840 回答