带有自动生成 ID 的 Doctrine 一对多映射

问题描述 投票:0回答:0

我有两个班级

Author
Posts
。一个作者可以有很多帖子,
posts
表有一个由
author_id
引用的作者。我想告诉 Doctrine 在从数据库中获取自动生成的 id 后填充
author_id
。这可能吗?

#[Entity]
#[Table(name: 'authors')]
class Author {

    #[Id]
    #[GeneratedValue]
    #[Column]
    private ?int $id = null;

    #[OneToMany(mappedBy: 'authorId', targetEntity: Post::class, cascade: ['persist'])]
    private ?Collection $posts;

    public function __construct(Collection $posts) {
      $this->posts = $posts;
    }
}
#[Entity]
#[Table(name: 'posts')]
class Post {

    #[Id]
    #[GeneratedValue]
    #[Column]
    private ?int $id = null;

    #[Column]
    #[ManyToOne(targetEntity: Author::class, inversedBy: 'id')]
    #[JoinColumn(name: 'author_id', referencedColumnName: 'id')]
    private ?int $authorId = null,
}

为了保存数据,我创建了一个

ArrayCollection
Post
空值,因为所需的数据应该由 Doctrine 处理。

$posts = new ArrayCollection([
  new Post(null, null),
  new Post(null, null)
]);

$author = new Author(posts: $posts);

$em->persist($author);
$em->flush();

谢谢!

doctrine-orm doctrine
© www.soinside.com 2019 - 2024. All rights reserved.