2

我正在尝试使用 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并在持久化时更新它。但这也意味着我必须在添加或删除孩子时更新父母。

你有任何解决这个问题的建议吗?

4

1 回答 1

4

我知道在 MongoDB 中测试数组不为空的最有效方法是使用“点表示法”$exists. 在查询生成器中有访问权限:

$qb = $dm->createQueryBuilder('Page')
    ->field('children.0')->exists(true);

这与 shell 中的情况相同:

db.collection.find({ "children.0": { "$exists": true } })

数组中第一个元素的索引也是如此0,并且仅在该数组中有一些内容时才存在。空数组不符合此条件。

于 2015-01-14T08:40:39.510 回答