2014-07-22 175 views
0

我有一個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; 

// ... 

回答

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) 
    ); 
} 
1

在palra答案的補體

儲存庫代碼:

namespace Foo\MyBundle\Entity; 

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

class CategoryRepository extends NestedTreeRepository 
{ 
} 

樹枝代碼示例(自舉):

<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>