我有两个班级
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();
谢谢!