2013-03-17 3 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가 질문을 함부로 나타내지 않았기 때문에) symfony2.2'-> getEntityManager()'가 사용되지 않고 symfony3와 함께 사용되었다는 것을 알려드립니다. 제거됩니다. 이미 symfony2.2를 사용하고 있다면'-> getManager()'를 사용하십시오. – DonCallisto

+7

@DonCallisto'getEntityManager'는 교리 방법이며 Symfony2와는 아무런 관련이 없습니다. symfony2는 자동으로 사용자 정의 저장소를 설정합니까? – Ocramius

+0

@Ocramius : 사실 당신 말이 맞아요. Symfony2.2와 doctrine (다른 버전)으로 동시에 업그레이드 한 것 같아서 혼란 스러웠습니다. 실제로 댓글은 내가 사용 중지 된 모든 전화를 제거하기 시작한 것과 같은 날 게시되었습니다. "mind-cut-and-paste"를했습니다. – DonCallisto

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

관련 문제