简体   繁体   中英

symfony2: Nested sets using RecursiveIteratorIterator

Im having problems following this tutorial: https://wildlyinaccurate.com/simple-nested-sets-in-doctrine-2

This is my code. As you can see in the comments, I can not iterate..

<?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
} 

What is shown in this article is not nested set. The best way to treat any kind of trees in symfony2 is to implement doctrine-extensions tree.

Please run one of those examples: https://github.com/Atlantic18/DoctrineExtensions/blob/master/doc/tree.md

The article that you linked is showing simple adjacent set and is applicable to any kind of application, not only Symfony. But in Symfony2 with Doctrine2 you can depend on doctrineExtensionBundle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM