0

我正在使用 NestedSet Tree 方法来构建库树。每个底层库也有一组对象。

这是在我的库实体类中定义的:

/**
 * @ORM\OneToMany(targetEntity="Object", mappedBy="library")
 */
private $objects;

在我的对象实体类中,我有:

/**
 * @ORM\ManyToOne(targetEntity="Library", inversedBy="objects")
 **/
private $library;

最后,我用

$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('AcmeDemoBundle:Library');
$arrayTree = $repo->childrenHierarchy();

执行 childrenHierarchy() 时,我得到了我的树,但没有 Objects 变量。例子:

[0] => Array
    (
        [id] => 1
        [name] => Foo
        [left] => 1
        [level] => 0
        [right] => 6
        [root] => 1
        [__children] => Array
            (
                [0] => Array
                    (
                        [id] => 2
                        [name] => Bar
                        [left] => 2
                        [level] => 1
                        [right] => 3
                        [root] => 1
                        [__children] => Array
                            (
                            )

                    )
4

1 回答 1

0

原来这不是那么容易解决的。

我最终编写了一个 DQL 查询,它获取所有库及其对象(使用连接,因此它只执行一个查询)。

然后我遍历层次结构并使用递归函数将所有内容连接在一起:

$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('AcmeDemoBundle:Library');
$allLibraries = $repo->findAllJoinedToObject();
$arrayTree = $repo->childrenHierarchy();

// merge the objects into the tree
$merge = function(&$tree) use (&$merge, $allLibraries) {
    foreach($tree as &$library) {
        $id = $library['id'];
        $library['objects'] = $allLibraries[$id]['objects'];

        if(count($library['__children'])) {
            $merge($library['__children']);
        }
    }
};

$merge($arrayTree);

下面是我的findAllJoinedToObject方法:

public function findAllJoinedToObject()
{
    $query = $this->getEntityManager()
        ->createQuery('
            SELECT l, o FROM acmeDemoBundle:Library l INDEX BY l.id
            LEFT JOIN l.objects o INDEX BY o.id'
        );

    try {
        return $query->getArrayResult();
    } catch (\Doctrine\ORM\NoResultException $e) {
        return null;
    }
}
于 2013-03-21T12:50:56.460 回答