我在本教程中遇到问题: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
}
本文中显示的内容不是嵌套集。在 symfony2 中处理任何类型的树的最好方法是实现 doctrine-extension tree。
请运行以下示例之一:https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/tree.md
您链接的文章显示了简单的相邻集,适用于任何类型的应用程序,而不仅仅是Symfony。但是在带有 Doctrine2 的 Symfony2 中,你可以依赖 doctrineExtensionBundle。