17

I have two entities which are connected through a 1:1 relationship, e.g: MyEntity.idRelatedEntity I want to create a Doctrine query where I can retrieve data from MyEntity depending on a value from a certain column in RelatedEntity. Something like this (it doesn't work of course):

$entity = $em
    ->getRepository('MyBundle:RelatedEntity')
    ->createQueryBuilder('e')
    ->leftJoin('MyBundle:RelatedEntity', 'r')
    ->where('r.foo = 1')
    ->getQuery()
    ->getResult();

Any help would be much appreciated :)

1
  • Where are you writing this query ? It would help me to answer your question AND improve your code. is that in the MyEntityRepository ? Commented Aug 21, 2013 at 12:23

2 Answers 2

26
$entity = $em
    ->getRepository('MyBundle:MyEntity')
    ->createQueryBuilder('e')
    ->join('e.idRelatedEntity', 'r')
    ->where('r.foo = 1')
    ->getQuery()
    ->getResult();

Also left join makes no sense here (because of where clause that will make it work like inner join)

Sign up to request clarification or add additional context in comments.

4 Comments

Great! Thank you! Just a small correction, you missed the id part inside the join. It should read ->join('e.idRelatedEntity', 'r')
can you please tell from where this r come?
->join('e.idRelatedEntity', 'r'), here you define r as an alias, you can put whatever here
idRelatedEntity is the name of the main table column which related to other table, Ex for product table related field is category so then the join will be ->join('e.category', 'r')
18

Note that you should write this query in your MyEntityRepository

public function getMyEntityWithRelatedEntity($parameter) 
{
    $query = $this->createQueryBuilder('e')
        ->addSelect('r') // to make Doctrine actually use the join
        ->leftJoin('e.relatedEntity', 'r')
        ->where('r.foo = :parameter')
        ->setParameter('parameter', $parameter)
        ->getQuery();

    return $query->getResult();
}

And then use it in your controller/service :

$manager = $this->getDoctrine()->getManager();
$results = $manager->getRepository(MyEntity::class)->getMyEntityWithRelatedEntity(1);

1 Comment

Nice one (and cleaner). Will take into account for the next time. For now I'm using @Uriziel answer :) Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.