Reputation: 965
I have a Category
entity designed to represent a Forum category. I used StofDoctrineExtensionsBundle
in order to use its Tree
annotation, in order to have a hierarchy in categories. Now, I would like to represent that hierarchy in a string, some like Category/Subcategory/Subsubcategory/Foo
. How can I get all the hierarchy in an unique request with 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;
// ...
Upvotes: 0
Views: 3428
Reputation: 3413
In complement of palra answer
The repository code :
namespace Foo\MyBundle\Entity;
use Doctrine\ORM\EntityRepository;
use Gedmo\Tree\Entity\Repository\NestedTreeRepository;
class CategoryRepository extends NestedTreeRepository
{
}
A Twig code example (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>
Upvotes: 1
Reputation: 965
I finally found how to do it :
Gedmo\Tree\Entity\Repository\NestedTreeRepository
getPath($node)
on it.Example :
// Assuming $category is provided by a ParamConverter
public function indexAction(Category $category = null)
{
return array(
'category' => $category,
'path' => $this->repo->getPath($category)
);
}
Upvotes: 0