递归实体原则

Recursive entity Doctrine

我想在我的网站上制作一个导航栏。

我有一个 SQL table 菜单。菜单可以有子菜单等....

CREATE TABLE IF NOT EXISTS MENU
(
    menu_Id INT AUTO_INCREMENT NOT NULL,
    nom VARCHAR(100) NOT NULL,
    route VARCHAR(255) NOT NULL,
    parent INT NULL,
    CONSTRAINT pk_MENU PRIMARY KEY (menu_Id),
    CONSTRAINT fk_MENU_MENU FOREIGN KEY (parent) REFERENCES MENU(menu_Id)
);

而且我在实体文件夹的 symfony 项目中有一个 class。

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity
 * @ORM\Table(name="menu")
 */
class Menu
{
    /**
     * @ORM\Column(name="menu_Id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(name="nom", type="string", length=100)
     */
    protected $lib;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $route;

    /**
     * @ORM\OneToMany(targetEntity="Menu", mappedBy="parent")
     */
    protected $listeSousMenus;

    //... GETTERS AND SETTERS ...
}

当我显示页面时,出现以下错误:

An exception has been thrown during the rendering of a template ("Notice: Undefined index: parent") in bandeau.html.twig at line 23.

我该如何解决这个错误?如何使用递归子项实现我的菜单?

错误很明确:您的父字段在哪里?

您需要添加一位家长属性:

/**
* @ORM\ManyToOne(targetEntity="Menu", inversedBy="listeSousMenus")
* @ORM\JoinColumn(name="parent", referencedColumnName="menu_Id")
*/
protected $parent;

查看文档中的这个示例:http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-many-self-referencing

<?php
/** @Entity */
class Category
{
    // ...
    /**
     * @OneToMany(targetEntity="Category", mappedBy="parent")
     */
    private $children;

    /**
     * @ManyToOne(targetEntity="Category", inversedBy="children")
     * @JoinColumn(name="parent_id", referencedColumnName="id")
     */
    private $parent;
    // ...

    public function __construct() {
        $this->children = new \Doctrine\Common\Collections\ArrayCollection();
    }
}