简体   繁体   中英

How to load all associations for a result set in a single query in Doctrine2

I have some pretty basic entities, containing stories and tags, which I'm trying to load as efficiently as possible.

When I query for stories like this:

SELECT a FROM Foo\Article a WHERE a.id IN (1,2,3,4,5)

I see see the following SQL queries being run:

SELECT f0_.id AS id_0, f0_.title AS title_1 FROM foo_article f0_ WHERE f0_.id IN (1, 2, 3)
SELECT t0.name AS name_1, t0.article_id AS article_id_2 FROM foo_tag t0 WHERE t0.article_id = 1
SELECT t0.name AS name_1, t0.article_id AS article_id_2 FROM foo_tag t0 WHERE t0.article_id = 2
SELECT t0.name AS name_1, t0.article_id AS article_id_2 FROM foo_tag t0 WHERE t0.article_id = 3

Where I would like to see this:

SELECT f0_.id AS id_0, f0_.title AS title_1 FROM foo_article f0_ WHERE f0_.id IN (1, 2, 3)
SELECT t0.name AS name_1, t0.article_id AS article_id_2 FROM foo_tag t0 WHERE t0.article_id IN (1, 2, 3);

Source code looks like this. Abbreviated from the actual code.

<?php
namespace Foo;

use Doctrine\ORM\Mapping as ORM;

/**
 * Class Tag
 *
 * @ORM\Entity()
 * @ORM\Table(name="foo_tag")
 *
 * @package Foo
 */
class Tag {

    /**
     * @ORM\Column(type="string")
     * @ORM\Id()
     */
    protected $name;

    /**
     * @ORM\ManyToOne(targetEntity="\Foo\Article",cascade={"persist"},fetch="LAZY",inversedBy="tags")
     * @ORM\Id()
     */
    protected $article;
}

/**
 * Class Article
 *
 * @ORM\Entity()
 * @ORM\Table(name="foo_article")
 *
 * @package Foo
 */
class Article {

    /**
     * @ORM\Id @ORM\Column(type="integer", name="id") @ORM\GeneratedValue
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $title;

    /**
     * @ORM\OneToMany(targetEntity="\Foo\Tag",mappedBy="article",cascade={"persist"},fetch="EAGER")
     */
    protected $tags;

}

One possible approach I was thinking about myself would be adding something like this to my repository class. But it just doesn't feel quite right just yet. I want something that's more portable to other associations, works every time the Entity is queried, and also works with Paginated queries.

Perhaps something in a postLoad-like event, that covers an entire result set (instead of the per-entity postLoad).

$qb = $entityManager->getRepository('Foo\Article')->createQueryBuilder('a')
    ->where('a.id IN (1,2,3)');

$list = $qb->getQuery()->execute();

/** @var Foo\Article[] $indexed */
$indexed = array_reduce($list, function($result, \Foo\Article $article) {
    $result[$article->getId()] = $article;
    return $result;
}, Array());

$tags = $entityManager->getRepository('Foo\Tag')->createQueryBuilder('t')
    ->where('t.article IN (:ids)')
    ->setParameter('ids', $indexed)
    ->getQuery()->execute();

array_map(function(\Foo\Tag $tag) use ($indexed) {

    /** @var \Doctrine\ORM\PersistentCollection $collection */
    $collection = $tag->getArticle()->getTags();
    $collection->add($tag);
    $collection->setInitialized(true);

}, $tags);

foreach($indexed as $article) {
    $article->getTags()->takeSnapshot();
    $article->getTags()->setInitialized(true);
}

/** @var Foo\Article $article */
// and now use the Articles and Tags, to make sure that everything is loaded
foreach($list as $article) {
    $tags = $article->getTags();
    print " - ".$article->getTitle()."\n";
    foreach($tags as $tag) {
        print "   - ".$tag."\n";
    }
}

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