(DOCTRINE) mappedBy 和 inversedBy 以及 targetEntity 注释

(DOCTRINE) mappedBy and inversedBy and targetEntity annotations

inversedBy 注释以及 mappedBy 注释中包含哪些值? 还有什么是 targetEntity 和 referencedColumnName?

这是我的 comment entity 的例子。如您所见,在我的教程中它说要在 inversedBy 属性中写入字符串 comments 并在 targetREntity 属性中写入 \Application\Entity\Post

/**
 * This class represents a comment related to a blog post.
 * @ORM\Entity
 * @ORM\Table(name="comment")
 */
class Comment
{

  /**
   * @ORM\ManyToOne(targetEntity="\Application\Entity\Post", inversedBy="comments")
   * @ORM\JoinColumn(name="post_id", referencedColumnName="id")
   */
  protected $post;
}

对于这个,它表示 comments这个评论字符串到底指的是什么? 我不知道评论是什么意思。这是到 table 的映射,还是顶部 class 的 ORM 名称,或者其他什么。

此外,

以下是使用 mappedBy 的示例:

/**
 * @ORM\Entity
 * @ORM\Table(name="post")
*/
class Post 
{
  // Post status constants.
  const STATUS_DRAFT       = 1; // Draft.
  const STATUS_PUBLISHED   = 2; // Published.

  /**
   * @ORM\OneToMany(targetEntity="\Application\Entity\Comment", mappedBy="post")   
   * @ORM\JoinColumn(name="id", referencedColumnName="post_id")
   */
  protected $comments;

我开始阅读有关 owning sides and inverse sides click here 的内容,但它非常难以理解。

如果能提供有关任何内容的详细信息,那就太好了。

任何帮助都会很棒。

我不是教条期望的,但我曾经使用它有一段时间了,所以我会尝试解释我目前所知道的。

InversedBy 引用 Post 实体中的 $comments 属性(字段),反之亦然。

The inverse side has to use the mappedBy attribute of the OneToOne, OneToMany, or ManyToMany mapping declaration. The mappedBy attribute contains the name of the association-field on the owning side.

The owning side has to use the inversedBy attribute of the OneToOne, ManyToOne, or ManyToMany mapping declaration. The inversedBy attribute contains the name of the association-field on the inverse-side.

当您使用 @ORM\ManyToOne 注释时,您正在创建 n:1 relationship. There are three types of mapping:

  • 双向 - Post 可访问 Comment反之亦然
  • 单向 - Post $comments 字段充满 Comment 个实体,但您无法访问 Post 来自 Comment,因为它没有映射回
  • self-referencing - Category with with self-reference to parent Category 这是实体同款

TargetEntity 告诉您要与哪个实体建立关系。想象一下外键。创建外键时需要指定引用 table.

ReferencedColumnName 告诉应该为哪个列创建外键。

教义不是魔法。它只是对象关系映射。把它想象成你使用 SQL 来创建关系。很多东西都差不多。