symfony2:使用RecursiveIteratorIterator的嵌套集

时间:2014-12-05 00:20:21

标签: php symfony

我在学习本教程时遇到了问题:https://wildlyinaccurate.com/simple-nested-sets-in-doctrine-2

这是我的代码。正如你在评论中看到的那样,我无法迭代..

<?php
class Item
{

    /**
    * @ORM\Id
    * @ORM\Column(type="integer")
    * @ORM\GeneratedValue(strategy="AUTO")
    */
    protected $id;

    /**
    * @ORM\OneToMany(targetEntity="Item", mappedBy="parent", cascade={"remove"})
    * @ORM\OrderBy({"position" = "ASC"})
    */
    private $children;

    /**
    * @Gedmo\SortableGroup
    * @ORM\ManyToOne(targetEntity="Item", inversedBy="children")
    * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true)
    */
    private $parent;

    ...


///////////////////////////////////////

namespace Project\BackendBundle\Entity;
use Doctrine\Common\Collections\Collection;

class RecursiveCategoryIterator implements \RecursiveIterator
{
    private $_data;

public function __construct(Collection $data)
{
    $this->_data = $data;
}

public function hasChildren()
{
    return ( ! $this->_data->current()->getChildren()->isEmpty());
}

public function getChildren()
{
    return new RecursiveCategoryIterator($this->_data->current()->getChildren());
}

public function current()
{
    return $this->_data->current();
}

public function next()
{
    $this->_data->next();
}

public function key()
{
    return $this->_data->key();
}

public function valid()
{
    return $this->_data->current() instanceof Project\BackendBundle\Entity\Item;
}

public function rewind()
{
    $this->_data->first();
}
}

/////////////////////////////////

$repository = $this->getDoctrine()->getRepository('ProjectBackendBundle:Item');
$root_categories = $repository->findBy(array('parent' => null));
var_dump(count($root_categories));// this returns 2

$collection = new \Doctrine\Common\Collections\ArrayCollection($root_categories);
$category_iterator = new RecursiveCategoryIterator($collection);
$recursive_iterator = new \RecursiveIteratorIterator($category_iterator);

var_dump($recursive_iterator->hasChildren()); //returns true
foreach ($recursive_iterator as $index => $child_category)
{
  die("jfks"); //this is not shown
} 

1 个答案:

答案 0 :(得分:0)

本文中显示的内容不是嵌套集。 在symfony2中处理任何类型树的最佳方法是实现doctrine-extensions树。

请运行其中一个示例: https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/tree.md

您链接的文章显示简单的相邻集,适用于任何类型的应用程序,而不仅仅是Symfony。但是在使用Doctrine2的Symfony2中,你可以依赖于doctrineExtensionBundle。