According to the Doctrine 2 docs here you can create a hierarchy of entities using a class with self-reference one-to-many relationship. I want to be able to query all categories with all its related children.
At this moment when I dump from the controller the query returns 'uninitialized': #collection: ArrayCollection -elements: [].
I don't know how to adjust the QueryBuilder to hydrate the children.
Code inside the CategoryRepository:
public function retrieveHydratedCategories()
{
return $this->createQueryBuilder('c')
->select('c, p, b')
->leftJoin('c.products', 'p')
->leftJoin('p.brand', 'b')
->Where("c.isActive = 1")
->getQuery()
->execute();
}
My Category entity:
<?php
// src/Entity/Category.php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
/**
* @ORM\Entity(repositoryClass="App\Repository\CategoryRepository")
* @ORM\Table(name="categories")
*/
class Category
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string", length=25)
*/
private $name;
/**
* @ORM\Column(type="string", length=64)
*/
private $brand;
/**
* @ORM\Column(type="string", length=100)
*/
private $image;
/**
* One ProductCategory has Many ProductCategories.
* @ORM\OneToMany(targetEntity="Category", mappedBy="parent")
*/
private $children;
/**
* Many ProductCategories have One ProductCategory.
* @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
private $parent;
/**
* @ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="category")
*/
private $products;
public function __construct()
{
$this->products = new ArrayCollection();
$this->children = new ArrayCollection();
}
/**
* @return Collection|Product[]
*/
public function getProducts()
{
return $this->products;
}
public function getChildren()
{
return $this->children;
}
public function getParent()
{
return $this->parent;
}
public function getName()
{
return $this->name;
}
public function getId()
{
return $this->id;
}
public function getImage()
{
return $this->image;
}
public function setName($name)
{
$this->name = $name;
}
public function addChildren (Category $children)
{
$this->children[] = $children;
return $this;
}
public function setIsActive($isActive)
{
$this->isActive = $isActive;
}
public function getBrand()
{
return $this->brand;
}
}