2013-03-17 5 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(別のバージョン)に同時にアップグレードして、これを混乱させたようです。実際にコメントは私が廃止予定のコールをすべて削除するのと同じ日に掲示されています。私は「マインドカットアンドペースト」を行っています:) – DonCallisto

0

あなたが依存関係を注入するために多くのが好きなら、あなたが他の内側にそれを使用する1つを注入することができますので、サービスとしてあなたのリポジトリを宣言します。

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では、リポジトリを保存するためのプロパティ(setUserLakeRepository)を持つ必要があります。 $ userLakeRepository)。

関連する問題