Doctrine 2 self-referenced entity without unnecessary queries

旧时模样 提交于 2019-12-10 07:12:41

问题


I'm trying that a self-referenced entity stop from querying the database everytime I fetch the children of one object, and get the whole tree in one query.

This is my entity:

/**
 * @ORM\Entity(repositoryClass="ExampleRep")
 * @ORM\Table(name="example_table")
 */
class Example {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer", nullable=false);
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="Example", inversedBy="children")
     * @ORM\JoinColumn(name="parent", referencedColumnName="id", onDelete="SET NULL")
     */
    private $parent = null;

    /**
     * @ORM\OneToMany(targetEntity="Example", mappedBy="parent")
     */
    private $children;

}

And i'm calling my date using queryBuilder like:

$query = $this->createQueryBuilder('e');
$query->orderBy('e.parent', 'ASC');
$example_data = $query->getQuery()->getResult();

When I cycle my example_data and call getChildren, another query is made, even if that same object, was already called in the query.

I've followed the example here: Doctrine - self-referencing entity - disable fetching of children but when i do it, my getChildren returns nothing.

Is there a way to fetch my data without overloading the database with multiple requests?


回答1:


If you know the depth of your tree, you can just do a custom dql query and do:

return $this->createQueryBuilder('example')
    ->addSelect('children')
    ->leftJoin('example.children', 'children')
    ->addSelect('subChildren')
    ->leftJoin('children.children', 'subChildren')
;

Otherwise, and as stated here, you can generate a flat resultset, and then construct the tree from it.

I made this kind of implementation using materialized paths, but nothing forbids you to do it with foreign keys comparison:

https://github.com/KnpLabs/DoctrineBehaviors/blob/master/src/Knp/DoctrineBehaviors/ORM/Tree/Tree.php#L119

https://github.com/KnpLabs/DoctrineBehaviors/blob/master/src/Knp/DoctrineBehaviors/Model/Tree/Node.php#L219



来源:https://stackoverflow.com/questions/16715490/doctrine-2-self-referenced-entity-without-unnecessary-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!