Doctrine2 - Get entity ID before flush

ぃ、小莉子 提交于 2019-12-12 08:19:53

问题


Is there any way to get an entity ID before the persist/flush? I mean:

$entity = new PointData();
$form   = $this->createForm(new PointDataType(), $entity);

If I try $entity->getId() at this point, it returns nothing.

I can get it working by:

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

(supposing $em = $this->getDoctrine()->getEntityManager();)

How can I achieve this?


回答1:


If you want to know the ID of an entity before it's been persisted to the database, then you obviously can't use generated identifiers. You'll need to find some way to generate unique identifiers yourself (perhaps some kind of hash function can produce unique-enough values).

This is rarely a good idea, though, so you should be careful.

I would think very carefully about why I need to know the identifier before flush. Doctrine is quite good at letting you build up a big object graph, and persist/flush it all at once. It seems likely that you've got something ugly in your architecture that you're trying to work around. It might be a good idea to review that before going down the application-generated-id route.




回答2:


You can use the @PostPersist annotation. A method annotated with that will be executed just before the flush terminate and the entity Id is available already.

https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/events.html

postPersist - The postPersist event occurs for an entity after the entity has been made persistent. It will be invoked after the database insert operations. Generated primary key values are available in the postPersist event.

<?php

use Doctrine\ORM\Mapping as ORM;

/** 
 * @ORM\Entity 
 * @ORM\HasLifecycleCallbacks 
 */
class PointData
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
     private $id;

     ...

     /** 
      * @ORM\PostPersist 
      */
     public function onPostPersist()
     {
         // Put some simple logic here that required the auto-generated Id.
     }

     ...

}



回答3:


you can use an auto generate ID to get a key like universally unique identifiers (UUID) or you can take the events of symfony: postFlush - The postFlush event occurs at the end of a flush operation.



来源:https://stackoverflow.com/questions/10485591/doctrine2-get-entity-id-before-flush

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