2017-09-29 12:46 阅读 30


I have problem with comments display in twig. They are visible if I list them all but I need them to be nested.

This is entity, I thought it should be referenced like this:

 * @var \AppBundle\Entity\Comment
 * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Comment")
 * @ORM\JoinColumn(name="parentId", referencedColumnName="id")
private $parentId;

Controller is simple, fetch all comments from db and returns array( with, and without parentId) Following some instruction i added this to main twig file:

<!-- Comments and omments with parentId -->
{% include 'front/main/comments-main.html.twig' with {'commments':comments} %}

Listing all comments works. But in included twig it seems this peace of code

{% if comment.parentId != null %}
            {% set children = [] %}
            {% set children = children|merge([ comment ]) %}
            {% include 'front/main/comments-main.html.twig' with {'comments':children} %}
        {% endif %}

does not work. If I echo something it is displayed in the right place, under comment with that id. But with that lines inside if not. Page load very slow and never ends. Like infinite loop. What I am doing wrong?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanjinchi1982 duanjinchi1982 2017-09-30 13:00

    Well, I did it. It was problem with infinite loop but because I was dealing with parentId, and I was following instructions of a someone who was dealing with object.children. So I had to make relation to be Many to One self-directional

    // ...
     * One Category has Many Categories.
     * @OneToMany(targetEntity="Category", mappedBy="parent")
    private $children;
     * Many Categories have One Category.
     * @ManyToOne(targetEntity="Category", inversedBy="children")
     * @JoinColumn(name="parent_id", referencedColumnName="id")
    private $parent;
    // ...
    public function addChild(Comment $child) {
       $this->children[] = $child;
    public function __construct() {
        $this->children = new \Doctrine\Common\Collections\ArrayCollection();

    (from http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-many-self-referencing) And to make small change in controler to set children.Before flush()

            $parent = $comment->getParentId();

    And in twig, in subtemplate I already had, inside the loop

        {% if comment.children is defined %}
            {% include 'front/main/comments-main.html.twig' with {'comments':comment.children} %}
        {% endif %}

    Hope to save some minutes to someone, I lost hours!

    点赞 评论 复制链接分享