我正在尝试使用 Doctrine MongoDB 构建一个延迟加载树。我的文档结构如下:
/**
* @ODM\Document(repositoryClass="CmsPage\Repository\PageRepository")
*/
class Page
{
/**
* @ODM\String
* @var string
*/
protected $title;
/**
* @ODM\ReferenceOne(targetDocument="CmsPage\Document\Page", inversedBy="children")
* @ODM\Index
* @var Page
*/
protected $parent;
/**
* @ODM\ReferenceMany(
* targetDocument="CmsPage\Document\Page", mappedBy="parent",
* sort={"title": "asc"}
* )
* @var array
*/
protected $children;
/**
* Default constructor
*/
public function __construct()
{
$this->children = new ArrayCollection();
}
/**
* @return ArrayCollection|Page[]
*/
public function getChildren()
{
return $this->children;
}
/**
* @param ArrayCollection $children
*/
public function setChildren($children)
{
$this->children = $children;
}
/**
* @return Page
*/
public function getParent()
{
return $this->parent;
}
/**
* @param Page $parent
*/
public function setParent($parent)
{
$this->parent = $parent;
}
/**
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* @param string $title
*/
public function setTitle($title)
{
$this->title = $title;
}
}
以下代码将检索给定页面的所有子项:
$page = $pageRepo->find('foo');
$children = [];
foreach ($page->getChildren() as $childPage) {
$children[] = [
'id' => $childPage->getId(),
'slug' => $childPage->getSlug(),
'leaf' => ($childPage->getChildren()->count() == 0)
];
这按预期工作,但将为每个子页面执行单独的查询以检查它是否是叶子。在处理具有大量子节点的大树时,效率将不高。
我可以在我的页面文档中引入一个布尔值isLeaf
并在持久化时更新它。但这也意味着我必须在添加或删除孩子时更新父母。
你有任何解决这个问题的建议吗?