Symfony
0
Вклад в тег
<?php
// src/Acme/DemoBundle/Entity/Category.php
namespace Acme\DemoBundle\Entity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* @Gedmo\Tree(type="nested")
* @ORM\Table(name="categories")
* use repository for handy tree functions
* @ORM\Entity(repositoryClass="Gedmo\Tree\Entity\Repository\NestedTreeRepository")
*/
class Category
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue
*/
private $id;
/**
* @Gedmo\Translatable
* @ORM\Column(name="title", type="string", length=64)
*/
private $title;
/**
* @Gedmo\TreeLeft
* @ORM\Column(name="lft", type="integer")
*/
private $lft;
/**
* @Gedmo\TreeLevel
* @ORM\Column(name="lvl", type="integer")
*/
private $lvl;
/**
* @Gedmo\TreeRight
* @ORM\Column(name="rgt", type="integer")
*/
private $rgt;
/**
* @Gedmo\TreeRoot
* @ORM\Column(name="root", type="integer", nullable=true)
*/
private $root;
/**
* @Gedmo\TreeParent
* @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $parent;
/**
* @ORM\OneToMany(targetEntity="Category", mappedBy="parent")
* @ORM\OrderBy({"lft" = "ASC"})
*/
private $children;
/**
*
* @Gedmo\Translatable
* @Gedmo\Slug(fields={"title"})
* @ORM\Column(name="slug", type="string", length=128)
*/
private $slug;
public function getId()
{
return $this->id;
}
public function getSlug()
{
return $this->slug;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
public function setParent(Category $parent = null)
{
$this->parent = $parent;
}
public function getParent()
{
return $this->parent;
}
}
use Acme\DemoBundle\Entity\Category as CategoryEntity;
// ... your code before
$em = $this->getDoctrine()->getManager();
$cat1= new CategoryEntity();
$cat1->setTitle('Фрукты');
$subcat = new CategoryEntity();
$subcat->setTitle('Экзотические');
$subcat->setParent($cat1);
$cat2 = new CategoryEntity();
$cat2->setTitle('Овощи');
$em->persist($cat1);
$em->persist($cat2);
$em->persist($subcat);
$em->flush();
// ...
$categoryEntity = $this->em->getRepository('Acme\DemoBundle\Entity\Category');
$categories = $categoryEntity->childrenHierarchy();
// ...