简体   繁体   中英

Simplifying a query in symfony2

(I'm not sure how to make the title more clear - feel free to edit it)

I have two tables with wines and wineries . Every wine has one winery assigned to it.
If I want to produce a list of all wines with the corresponding winery, I can do this:

$entities = $em->getRepository('MyBundle:Wine')->findAll();

and

{% for entity in entities %}
  {{ entity.winery.name }} {{ entity.name }} <br />
{% endfor %}

The problem with this solution is that there is an extra query made for every winery which I want to prevent.

I tried the technique used in the symfony2 manual but I was unable to get it to work (does it work just for a single result?).

Normally with SQL, I would simply do a LEFT JOIN but I just can't figure out how to accomplish that in Doctrine2.

$qb = $this->createQueryBuilder('w', 'wnr');
$qb->leftJoin('w.winery', 'wnr');
$qb->orderBy('w.name', 'ASC');

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

???

I'd be thankful for any help!

Did you select Winery in your DQL query?

$entities = $em->getRepository('MyBundle:Wine')
    ->createQueryBuilder('w')
    ->select('w, wnr')
    ->leftJoin('w.winery', 'wnr');
    ->getQuery()
    ->getResult();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM