问题 Symfony/Doctrine:One-To-Many - Self-referencing 在主键上

Problem Symfony/Doctrine : One-To-Many - Self-referencing on a primary key

我想要一个带有标识符的“post”。通过存储他的 parent.

的标识符,可以将此归入另一个“post”

我试过这样做:

class Post {
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * @ORM\OneToMany(targetEntity="Post", mappedBy="Id_Post_Parent")
     */
    private $Id_Post;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Post", inversedBy="Id_Post")
     * @ORM\JoinColumn(name="Id_Post", referencedColumnName="Id_Post", nullable=true)
     */
    private $Id_Post_Parent;
    ...
}

但是我在检查 doctrine:schema:validate 时遇到了这个错误:

[FAIL] The entity-class App\Entity\Post mapping is invalid:

  • The association App\Entity\Post#Id_Post_Parent refers to the inverse side field App\Entity\Post#Id_Post which is not defined as association.
  • The association App\Entity\Post#Id_Post_Parent refers to the inverse side field App\Entity\Post#Id_Post which does not exist.
  • The referenced column name 'Id_Post' has to be a primary key column on the target entity class 'App\Entity\Post'.

有人可以帮我解决这个问题吗?

您的结构存在小的逻辑错误 - 您的 ID_Post 变量试图同时作为主键(ID)和集合关联端。我没有详细检查此语法(您可以从学说文档中找到此关联的示例以及大多数其他关联:https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/association-mapping.html#one-to-many-self-referencing),但基本上您需要将子关联单独添加到您的像这样的实体:

class Post 
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Post", inversedBy="postChildren")
     * @ORM\JoinColumn(name="id_parent_post", referencedColumnName="id", nullable=true)
     */
    private $postParent;

    /**
     * @ORM\OneToMany(targetEntity="Post", mappedBy="postParent")
     */
    private $postChildren;

    public function __construct() {
        $this->postChildren = new \Doctrine\Common\Collections\ArrayCollection();
    }    
}