How persist new Entity in Doctrine 2 prePersist method?

穿精又带淫゛_ 提交于 2020-12-12 11:34:45

问题


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?


回答1:


You need to use the LifecycleEventArgs to get EntityManager and be able to persist Entity in prePersist method. You can retrieve it like that :

<?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
        }
    }
}


来源:https://stackoverflow.com/questions/7838706/how-persist-new-entity-in-doctrine-2-prepersist-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!