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?
If you know the depth of your tree, you can just do a custom dql query and do:
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