2013-03-17 43 views
18

我需要來自2個不同實體的值。我不知道該怎麼辦。 我想這至今:如何在Doctrine2/Symfony2的倉庫中獲得外部倉庫?

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

} 

不工作 請幫助。 感謝

回答

34

可以通過調用Doctrine\ORM\EntityRepository#getEntityManager()訪問EntityManager

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

因爲你沒在你的答案指定它(和OP沒有問題spicify吧),我想讓你知道,因爲symfony2.2' - > getEntityManager()'已被廢棄,用symfony3,它將被刪除。 使用' - > getManager()'如果你已經有symfony2.2 – DonCallisto 2013-03-18 08:04:27

+7

@DonCallisto'getEntityManager'是一種教條的方法,並沒有任何與Symfony2的。 symfony2是否自動設置自定義存儲庫? – Ocramius 2013-03-18 17:58:26

+0

@Ocramius:其實你是對的。所以看起來我已經升級到symfony2.2和教條(另一個版本),並且混淆了這一點。其實評論發佈在同一天,我開始刪除所有不推薦使用的電話,我已經做了一個「思維剪貼」:) – DonCallisto 2013-03-18 18:15:08

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