如何在 Doctrine 2 prePersist 方法中持久保存新实体?
我有一个带有 @HasLifecycleCallbacks 的实体,用于定义 prePersist 和 preUpdate 方法。
我的 PrePersist 方法是
/**
* @ORM\OneToMany(targetEntity="Field", mappedBy="service", cascade={"persist"}, orphanRemoval=true)
*/
protected $fields;
/**
* @PrePersist()
*/
public function populate() {
$fieldsCollection = new \Doctrine\Common\Collections\ArrayCollection();
$fields = array();
preg_match_all('/%[a-z]+%/', $this->getPattern(), $fields);
if (isset($fields[0])) {
foreach ($fields[0] as $field_name) {
$field = new Field();
$field->setField($field_name);
$field->setService($this);
$fieldsCollection->add($field);
}
$this->setFields($fieldsCollection);
}
}
我希望这可以持久化我的 Field 实体,但我的表是空的。 我应该使用 EntityManager 吗?我如何在我的实体中检索它?
I've a Entity with @HasLifecycleCallbacks for define prePersist and preUpdate method.
My PrePersist method is
/**
* @ORM\OneToMany(targetEntity="Field", mappedBy="service", cascade={"persist"}, orphanRemoval=true)
*/
protected $fields;
/**
* @PrePersist()
*/
public function populate() {
$fieldsCollection = new \Doctrine\Common\Collections\ArrayCollection();
$fields = array();
preg_match_all('/%[a-z]+%/', $this->getPattern(), $fields);
if (isset($fields[0])) {
foreach ($fields[0] as $field_name) {
$field = new Field();
$field->setField($field_name);
$field->setService($this);
$fieldsCollection->add($field);
}
$this->setFields($fieldsCollection);
}
}
I hoped that this could persist my Field entities, but my table is empty.
Should I use an EntityManager? How can I retrieve it within my Entity?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要使用 LifecycleEventArgs 来获取 EntityManager 并能够在 prePersist 方法中持久保存实体。您可以这样检索它:
You need to use the LifecycleEventArgs to get EntityManager and be able to persist Entity in prePersist method. You can retrieve it like that :