递归实体原则

问题描述 投票:0回答:1

我想在我的网站上创建一个导航栏。

我有一个SQL表菜单。菜单可以具有子菜单,等等。]

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项目的Entity文件夹中有一个类。

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

显示页面时出现此错误:

[在第23行的bandeau.html.twig中呈现模板(“ Notice:Undefined index:parent”)的过程中引发了异常。

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

php symfony doctrine-orm symfony1
1个回答
6
投票

错误是显式的:您的父字段在哪里?

您需要添加父属性:

/**
* @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();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.