0
我目前正在使用自引用實體,我必須建立一個基於該實體的小列表結構(<ul><li>
)。然而,列表必須考慮到深度,所以我需要使用父/子關係作爲我的渲染器的基礎。這裏的原始實體:從原則2呈現嵌套的類別實體
<?php
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
* @ORM\Table(name="categories")
*/
class Category
{
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
*/
protected $id;
/**
* @ORM\Column(type="string", length=255)
*/
protected $name;
/**
* @var Category
*
* @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id", nullable=true, onDelete="CASCADE")
*/
protected $parent;
/**
* @var Collection
*
* @ORM\OneToMany(
* targetEntity="Category",
* mappedBy="parent",
* cascade={"ALL"}
*)
*/
protected $children;
public function __construct()
{
$this->children = new ArrayCollection();
}
public function getId():
{
return $this->id;
}
public function setId(int $id)
{
$this->id = $id;
}
public function getName()
{
return $this->name;
}
public function setName(string $name)
{
$this->name = $name;
}
public function getParent()
{
return $this->parent;
}
public function setParent(Category $parent)
{
$this->parent = $parent;
}
public function setChildren(array $children)
{
$this->children = $children;
}
public function getChildren()
{
return $this->children;
}
public function addChild(Category $category)
{
if (!$this->children->contains($category)) {
$category->setParent($this);
$this->children->add($category);
}
}
public function removeChild(Category $category)
{
if ($this->children->contains($category)) {
$this->children->removeElement($category);
}
}
}
我已經實現受此啓發非常幼稚的做法:https://wildlyinaccurate.com/simple-nested-sets-in-doctrine-2/
然而,這種基於深度的填充邏輯不幫我<ul><li>
結構。有沒有人推薦任何將自引用對象呈現爲HTML列表的方式?
這是幾乎沒有可擴展性。如果超過3個級別會怎麼樣? – vinnylinux