显示树层次结构

时间:2014-07-22 17:09:19

标签: symfony doctrine-orm stofdoctrineextensions

我有一个Category实体,旨在代表论坛类别。我使用StofDoctrineExtensionsBundle来使用其Tree注释,以便在类别中使用层次结构。现在,我想在字符串中表示该层次结构,有些像Category/Subcategory/Subsubcategory/Foo。如何使用Doctrine在唯一请求中获取所有层次结构?

// Category.php

use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;

/**
 * @Gedmo\Tree(type="nested")
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="PC\ForumBundle\Entity\Repository\CategoryRepository")
 */
class Category
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue
     */
    private $id;

    /**
     * @ORM\Column(length=64)
     */
    private $title;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $description;

    /**
     * @Gedmo\Slug(fields={"title"})
     * @ORM\Column(length=64, unique=true)
     */
    private $slug;

    /**
     * @Gedmo\TreeLeft
     * @ORM\Column(type="integer")
     */
    private $lft;

    /**
     * @Gedmo\TreeRight
     * @ORM\Column(type="integer")
     */
    private $rgt;

    /**
     * @Gedmo\TreeParent
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
     */
    private $parent;

    /**
     * @Gedmo\TreeRoot
     * @ORM\Column(type="integer", nullable=true)
     */
    private $root;

    /**
     * @Gedmo\TreeLevel
     * @ORM\Column(name="lvl", type="integer")
     */
    private $level;

    /**
     * @ORM\OneToMany(targetEntity="Category", mappedBy="parent")
     */
    private $children;

// ...

2 个答案:

答案 0 :(得分:1)

补充palra答案

存储库代码:

namespace Foo\MyBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Gedmo\Tree\Entity\Repository\NestedTreeRepository;

class CategoryRepository extends NestedTreeRepository
{
}

Twig代码示例(bootstrap):

  <ol class="breadcrumb">
      <li><a href="{{ path('...') }}"><i class="fa fa-home"></i></a></li>
      {% for p in path %}
      <li><a {% if loop.last  %}class="active"{% endif %}
       href="{{ path(...) }}">{{ p.name }}</i></a></li>
      {% endfor %}
 </ol>

答案 1 :(得分:0)

我终于找到了如何做到这一点:

  • 使您的存储库类扩展Gedmo\Tree\Entity\Repository\NestedTreeRepository
  • 调用方法getPath($node)

示例:

// Assuming $category is provided by a ParamConverter
public function indexAction(Category $category = null)
{
    return array(
        'category' => $category,
        'path' => $this->repo->getPath($category)
    );
}