Kdyby\Doctrine – Stromová struktura

- thm
 - Člen | 151
 
Mohu se zeptat, jak řešíte stromové struktury v Doctrine?
Začínám, zkouším, napsal jsem entitu MenuItem. Chtěl bych implementovat
metodu getChildren() tak aby vracela pole MenuItems, vůbec nevím jak?
Také nevím, jestli je to vhodné řešení – asi to takto bude k vypsání
celé stromové struktury procházením menuItems a volání getChildren()
generovat spoustu dotazů na DB (?).
Dále bych si pak představoval metodu addChild(MenuItem $menuItem), která
připojí MenuItem pod toho, na kterém to volám. Měl bych tyto funkce
implementovat zde, nebo si vytvořit nějakého MenuManagera?
namespace App\Model;
use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Entity
 */
class MenuItem
{
      use \Kdyby\Doctrine\Entities\MagicAccessors;
      use \Kdyby\Doctrine\Entities\Attributes\Identifier;
      /** @ORM\Column(type="string") */
      protected $name;
      /** @ORM\ManyToOne(targetEntity="MenuItem") */
      protected $parent;
      /**
       * @return array of MenuItem
       */
      public function getChildren()
      {
            //Jak implementovat toto?
      }
      /**
       * Adds child MenuItem under $this MenuItem
       * @param \App\Model\MenuItem $menuItem
       */
      public function addChild(MenuItem $menuItem)
      {
            //A případně toto?
      }
}
				
- David Matějka
 - Moderator | 6445
 
Nejpr si udelej pro parent inverzni relaci „children“, ktera bude OneToMany.
Pro optimalizace se vetsinou pouziva bud closure table nebo nested tree. Koukni na https://github.com/…neExtensions a https://github.com/…ineBehaviors .. existuji i nejaky integrace do nette

- David Matějka
 - Moderator | 6445
 
namespace App\Model;
use Doctrine\ORM\Mapping as ORM;
/**
 * @ORM\Entity
 */
class MenuItem
{
      use \Kdyby\Doctrine\Entities\MagicAccessors;
      use \Kdyby\Doctrine\Entities\Attributes\Identifier;
      /** @ORM\Column(type="string") */
      protected $name;
//                                               _v_ tohle je tu nove _v_
      /** @ORM\ManyToOne(targetEntity="MenuItem", inversedBy="children") */
      protected $parent;
      /** @ORM\OneToMany(targetEntity="MenuItem", mappedBy="parent") */
      protected $children;
      public function __construct()
      {
            $this->children = new \Doctrine\Common\Collections\ArrayCollection;
      }
      /**
       * @return array of MenuItem
       */
      public function getChildren()
      {
            return $this->children;
      }
      /**
       * Adds child MenuItem under $this MenuItem
       * @param \App\Model\MenuItem $menuItem
       */
      public function addChild(MenuItem $menuItem)
      {
            $menuItem->parent = $this;
            $this->children->add($menuItem);
      }
}