2012-03-29 11 views
8

Diciamo che ho un'entità Account e un'entità AccountData (che memorizza alcune proprietà meno utilizzate, come genere, ecc.).Doctrine 2: Come cercare un'entità in base al valore dell'associazione?

La relazione tra Account e Dati conto è uno a uno e l'account "possiede" Dati conto.

Sto cercando di capire, utilizzando Doctrine 2/Symfony 2, come richiamare un account in base a una proprietà in AccountData.

Ad esempio, come è possibile cercare tutti gli account con AccountData-> gender = 'female'?

risposta

15

Utilizzando Query Builder di Doctrine come questo dovrebbe fare il trucco:

$repository = $this->getDoctrine()->getRepository('YourBundle:Account'); 

$query = $repository->createQueryBuilder('a') 
    ->join('a.AccountData', 'd') 
    ->where('d.gender = :gender') 
    ->setParameter('gender', 'female') 
    ->getQuery(); 

$female_accounts = $query->getResult(); 

È possibile controllare http://symfony.com/doc/current/book/doctrine.html#joining-to-related-records per un esempio utilizzando invece una classe di repository.

Spero che aiuti.

+1

Dovrebbe essere unito ('a.AccountData', 'd')? –

+0

@g, sei corretto. – orourkedd

1

Qualcosa di simile:

$em = $this->getEntityManager(); 
    $qb = $em->createQueryBuilder(); 

    $qb->addSelect('account'); 
    $qb->addSelect('accountData'); 

    $qb->from('ZaysoCoreBundle:Account','account'); 

    $qb->leftJoin('account.accountData', 'accountData'); 

    $qb->andWhere($qb->expr()->eq('accountData.gender',$qb->expr()->literal('female'))); 

    $accounts = $qb->getQuery()->getResult(); 

Il manuale è molto utile: http://docs.doctrine-project.org/projects/doctrine-orm/en/2.1/reference/query-builder.html