设置 Symfony 父子容器关系并创建树数组

时间:2021-03-02 13:28:33

标签: symfony5

我正在使用 symfony 5 并且对我的一个实体有一个 Self 引用,它通过 parentId 字段工作。我希望能够在我的控制器中读出整个树,并且最好在视图模板中关闭父级,直到你点击它,但那是另一个步骤。

我找到了以下内容并在我的控制器中尝试过,但是当我转储它时它是空的。我假设我必须运行 categoryTree 递归,所以我做错了什么,我如何在 symfony 中最好地实现它,当你期望大量数据时什么是最快的?

    function categoryTree($parentCategory = null) {
      if(!isset($a)){
        $a = array();
      }

      $em = $this->getDoctrine()->getManager();;
      $rows = $em->getRepository(Container::class)->findBy(array('parentCategory' => $parentCategory));
      foreach ($rows as $row) {
       
        array_push(
            $a,
            [
                $row->getCategoryId() => $row->getTitel(),
                'children' => $this->categoryTree($row->getCategoryId())
            ]
        );
       
      }

      return $a;
  }

class Container
{
/**
 * @ORM\ManyToOne(targetEntity=Category::class, inversedBy="childrenCategorys")
 * @ORM\JoinColumn(name="parent_id", referencedColumnName="category_id")
 */
private $parentCategory;

/**
 * @ORM\OneToMany(targetEntity=Category::class, mappedBy="parentCategory")
 */
private $childrenCategorys;

0 个答案:

没有答案