3

我有一个评论实体(用于用户评论),我想在我的旧实体中添加一个新功能(可评论)。我创建了一个可评论的特征:

trait Commentable
{
    /**
     * List of comments
     *
     * @var Comment[]|ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Comment")
     */
    protected $comments;

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

    /**
     * Get Comments
     *
     * @return Comment[]|ArrayCollection
     */
    public function getComments()
    {
        return $this->comments;
    }

    /**
     * Add comment to the entity
     *
     * @param Comment $comment
     */
    public function addComment(Comment $comment)
    {
        $this->comments->add($comment);
    }
}

在旧实体中,我做了这样的事情:

class Image
{
    use Commentable {
        Commentable::__construct as private __commentableConstruct;
    }

    /** some stuff **/
}

评论类看起来像:

class Comment
{
    /**
     * Identifier
     *
     * @var int
     *
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

    /**
     * Comment owner
     *
     * @var User
     *
     * @ORM\ManyToOne(targetEntity="User", inversedBy="comments")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    protected $user;

    /**
     * Comment content
     *
     * @var string
     *
     * @ORM\Column(type="text")
     */
    protected $content;

    /**
     * @var Image
     *
     * @ORM\ManyToOne(targetEntity="Image", inversedBy="comments")
     */
    protected $image;
    /** all the classes using Commentable **/

    /** some stuff */
}

我认为这个想法还不错。我可以创建新行为并将其轻松添加到实体中。但我不喜欢 Comment 实体的想法。使用可评论特征添加所有类不是“有用的”。我收到了这个错误......但我不知道如何用特征来解决这个问题:

OneToMany mapping on field 'comments' requires the 'mappedBy' attribute.
4

2 回答 2

3

我解决了这个问题

trait Commentable
{
    /**
     * List of comments
     *
     * @var Comment[]|ArrayCollection
     *
     * @ORM\ManyToMany(targetEntity="XXXX\Entity\Comment")
     * @ORM\OrderBy({"createdAt" = "DESC"})
     */
    protected $comments;

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

    /**
     * Get Comments
     *
     * @return Comment[]|ArrayCollection
     */
    public function getComments()
    {
        return $this->comments;
    }

    /**
     * Add comment to the entity
     *
     * @param Comment $comment
     */
    public function addComment(Comment $comment)
    {
        $this->comments->add($comment);
    }
}
于 2013-07-26T11:53:38.263 回答
0

这不是特征问题,而是与映射/教义相关的问题。

根据文档,您的注释“@OneToMany”缺少配置

我想在您的 Image 类中,您应该覆盖用于映射的属性。

于 2013-07-17T10:15:57.560 回答