与 Doctrine 的关联映射

Association mapping with Doctrine

我有两个实体:

用户和 评论

每条评论只能有一个用户,但一个用户可以有多个评论。

我不确定我是想使用双向、带连接的单向 Table 还是自引用。

我只希望在调用评论对象时应用此关系。如果我在某处调用用户对象,我不希望一堆评论对象淹没用户对象。我应该采用哪种方法?

Symfony 的文档很好地解释了这个过程:http://symfony.com/doc/current/book/doctrine.html#fetching-related-objects

What's important is the fact that you have easy access to the product's related category, but the category data isn't actually retrieved until you ask for the category (i.e. it's "lazily loaded").

只需建立 ManyToOne 关系,只在需要时获取用户的评论。

User实体:

<?php
class User
{
    // ...

    /**
     * @ORM\OneToMany(targetEntity="Comment", mappedBy="author")
     */
    protected $comments;

    public function __construct()
    {
        $this->comments = new ArrayCollection();
    }
}

Comment实体:

<?php
class Comment
{
    // ...

    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="comments")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    protected $author;
}