Search code examples
symfonydoctrine-ormdoctrinedoctrine-query

Doctrine Query reverse join?


BDD Schema

I have these relations.

I need to retrieve all contents but order by star.content_Idcontent first.

It works with easy SQL:

SELECT content.idcontent
FROM content
LEFT JOIN star ON content.idcontent = star.content_Idcontent 
ORDER BY star.content_Idcontent DESC,content.idcontent

But I don't know how to do it with Doctrine because content is not the owner of the relation.

Must I create a bidirectional relation or is there a way to make it work?


Solution

  • You can create a query in ContentRepository like:

    $qb = $this
        ->createQueryBuilder('content')
        ->join(
             'App\Entity\Star',
             'star',
             \Doctrine\ORM\Query\Expr\LeftJoin::WITH,
             'content.idcontent = star.content_Idcontent '
             )
        ->orderBy('star.content_Idcontent', 'DESC')
    ;
    
    $qb->getResult();
    

    Assuming that your Entity Star is located in App\Entity\Star