Self relationship Doctrine

Asked

Viewed 270 times

1

I’m using Doctrine, and now I have the following problem.

I am making a register of menus system, where the same can have several "children" and their "children" can also have "children", and so on.

How will I realize this self-relationship with Doctrine?

I have already performed the mapping in the Menu class with the Annotations, but I could not understand how I will do this mapping in the query, so that when performing the search the menu object is already filled with all the items correctly.

Below is the mapping I performed in the Menu class:

/**
 * @ORM\Entity
 * @ORM\Table(name="tb_Menu")
 */
class Menu
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue("SEQUENCE")
     * @ORM\Column(type="integer", nullable=false)
     * @ORM\SequenceGenerator(sequenceName="sq_Menu")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Menu", inversedBy="menuFilho")
     * @ORM\JoinColumn(name="idMenuPai", referencedColumnName="id")
     */
    private $menuPai;

    /**
     * @ORM\OneToMany(targetEntity="Menu", mappedBy="menuPai")
     */
    private $menuFilho;

    /**
     * @ORM\Column(type="string", length=30, unique=true, nullable=false)
     */
    private $titulo;

    /** 
     * @ORM\Column(type="string", length=80)
     */
    private $descricao;

    /* 
     * Construtor
     */
    public function __construct() {
        $this->menuFilho = new ArrayCollection();
    }
}

1 answer

1

What you need to do is create a One-To-Many Self-referencing Relationship.

Read this section in the Doctrine documentation:

http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html#one-to-Many-self-referencing

Basically, you will use a single table to build the tree in your menu, and the rows of the child nodes will relate to their respective parent nodes through the same table.

In addition, there is a very interesting extension to the Doctrine, called Tree. With this extension you can build tree-like structures in your database (for example, your case of categories and sub-categories) and still render an HTML on top of that structure. See if it fits.

  • So Rodrigo I already read this article and I did the relationship as they explained, but I still don’t understand how I’m going to build my query to return the data. If you have an example there and can pass me I thank you.

  • I edited the answer by citing an extension to Doctrine to create structures similar to what you need. I use it here for the same purpose. See if it fits :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.