具有自引用和连接的Symfony 2多关联实体

时间:2017-02-24 18:20:43

标签: php symfony self-reference doctrine-query

我尝试制作经典的评论多级回复系统:

Comment 1
   Reply 1-1
     Reply 1-2
        Reply 1-3

所以我创建了2个实体评论回复定义:

class Comment
{
[...]
/**
 * @ORM\OneToMany(targetEntity="CommentBundle\Entity\Reply", mappedBy="comment")
 */
protected $replies;
[...]


class Reply
{
[...]
/**
 * @ORM\ManyToOne(targetEntity="CommentBundle\Entity\Comment", inversedBy="replies")
 */
protected $comment;

/**
 * children replies
 * @ORM\OneToMany(targetEntity="CommentBundle\Entity\Reply", mappedBy="reply")
 */
protected $replies;

/**
 * parent reply
 * @ORM\ManyToOne(targetEntity="CommentBundle\Entity\Reply", inversedBy="replies")
 * @ORM\JoinColumn(name="reply_id", referencedColumnName="id", nullable=true)
 */
protected $reply;
[...]

以及相关的查询:

$qrycomment = "SELECT a, b, c FROM CommentBundle:Comment a LEFT JOIN a.replies b LEFT JOIN b.replies c ";

$qryreply = "SELECT a, b FROM CommentBundle:Reply a LEFT JOIN a.replies b";  

我的问题:

案例1:执行qryreplies => 1个查询已执行=>行

查询1:获取reply1-1,reply1-2和reply1-3

案例2:执行qrycomment =>已执行多个查询=> KO

查询1:获得评论1-1,回复1-1

查询2:获取reply1-2

查询3:获取reply1-3

注意:

comment.twig:

{% for key,item in items %}
    {{ item.description }}<br>
    {% include "CommentBundle:Comment:Reply.twig" with {'items': item.getReplies } %}
{% endfor %}

Reply.twig

   {% for key,item in items %}
        Reply :
        {{ item.description }}
        {% include "CommentBundle:Comment:Reply.twig" with {'items': item.getReplies } %}
    {% endfor %}

我希望我的解释足够清楚。 谢谢你的帮助。

0 个答案:

没有答案