我有一个使用@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吗?如何在我的实体中检索它?
答案 0 :(得分:1)
您需要使用LifecycleEventArgs来获取EntityManager并能够将实体持久保存在prePersist方法中。您可以这样检索它:
<?php
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
class MyEventListener
{
public function preUpdate(LifecycleEventArgs $args)
{
$entity = $args->getObject();
$entityManager = $args->getObjectManager();
// perhaps you only want to act on some "Product" entity
if ($entity instanceof Product)
{
// do something with the Product
}
}
}