Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2: How to search for an entity by its association's value?

Let's say I have an Account entity, and an AccountData entity (which stores some less used properties, like gender, etc).

The relationship between Account and AccountData is one-to-one, and the Account "owns" AccountData.

I'm trying to figure out, using Doctrine 2 / Symfony 2, how to pull up an Account according to a property in AccountData.

For example, how do I search for all Accounts with AccountData->gender = 'female'?

like image 616
johnnietheblack Avatar asked Mar 29 '12 20:03

johnnietheblack


2 Answers

Using Doctrine's Query Builder like this should do the trick:

$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();

You can check http://symfony.com/doc/current/book/doctrine.html#joining-to-related-records for an example using a repository class instead.

Hope it helps.

like image 103
Juan Sosa Avatar answered Nov 18 '22 05:11

Juan Sosa


Something like:

    $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();

The manual is very useful: http://docs.doctrine-project.org/projects/doctrine-orm/en/2.1/reference/query-builder.html

like image 32
Cerad Avatar answered Nov 18 '22 05:11

Cerad