Witam.
Pracuje obecnie na Symfony 3.4.37 i posiadam tabele, która odnosi się do samej siebie w relacji One-To-Many. Jest to wzór kategorii i ich podkategorii. Niestety kiedy próbuje wyciągnąć dane dotyczące rodzica i dzieci to collection: ArrayCollection nie zawiera żadnych elementów. Szukałem już po internecie i dokumentacji. Może coś przeoczyłem, jestem dość nowy w tym temacie.
Fotka z bazy:
Jak widać relacje w bazie są jakie są i teraz dostaje takie info z dumpa"
Kod Entity:
<?php
namespace WL\AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* TestCat
*
* @ORM\Table(name="test_cat")
* @ORM\Entity(repositoryClass="WL\AppBundle\Repository\TestCatRepository")
*/
class TestCat
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string|null
*
* @ORM\Column(name="parent_id", type="integer", nullable=true)
*/
private $parent_id;
/**
* Many to One
* @ORM\ManyToOne (targetEntity="WL\AppBundle\Entity\TestCat", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id")
*/
private $parent;
/**
* @ORM\OneToMany (targetEntity="WL\AppBundle\Entity\TestCat", mappedBy="parent")
*/
private $children;
/**
* @var string
*
* @ORM\Column(name="description", type="text")
*/
private $description;
public function __construct(){
$this->children = new ArrayCollection();
}
/**
* @return Collection
*/
public function getChildren(): ?Collection{
return $this->children;
}
public function setParent($id):void{
$this->parent = $id;
}
/**
* Get id.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set parent.
*
* @param null $parent_id
* @return TestCat
*/
public function setParentId($parent_id = null)
{
$this->parent_id = $parent_id;
return $this;
}
/**
* Get parent.
*
* @return integer|null
*/
public function getParentId()
{
return $this->parent_id;
}
/**
* Set description.
*
* @param string $description
*
* @return TestCat
*/
public function setDescription(string $description)
{
$this->description = $description;
return $this;
}
/**
* Get description.
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
}
Wywołanie w Controllerze:
$em = $this->getDoctrine()->getManager();
$cats = $em->getRepository('WLAppBundle:TestCat')->findAll();
dump($cats[0]->getChildren());die;