无需不必要的查询

无需不必要的查询

本文介绍了教义2自引用实体,无需不必要的查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使自引用实体在每次获取一个对象的子代并在一次查询中获取整棵树时停止查询数据库.

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.

这是我的实体:

/**
 * @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;

}

我正在使用queryBuilder打电话给我的日期,

And i'm calling my date using queryBuilder like:

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

当我循环执行example_data并调用getChildren时,将进行另一个查询,即使该对象已在查询中被调用.

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

我在这里遵循了以下示例: Doctrine-自引用实体-禁止提取儿童,但是当我这样做时,我的getChildren什么也不返回.

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?

推荐答案

如果您知道树的深度,则可以执行自定义dql查询并执行以下操作:

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

这篇关于教义2自引用实体,无需不必要的查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 09:42