Doctrine2 - 在清洗之前获取实体ID [英] Doctrine2 - Get entity ID before flush

查看:154
本文介绍了Doctrine2 - 在清洗之前获取实体ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在持久性/刷新之前有没有办法获取实体ID?
我的意思是:

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

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

如果我尝试 $ entity-> getId()它不会返回任何东西。

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

我可以通过以下方式获得它:

I can get it working by:

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

(假设 $ em = $ this-> getDoctrine() - > getEntityManager()

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

如何实现?

推荐答案

如果要在实体持久保存到数据库之前知道实体的ID,那么您显然不能使用生成的标识符。您将需要找到一些方法来自己生成唯一的标识符(或许某种哈希函数可以产生足够的唯一值)。

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.

这篇关于Doctrine2 - 在清洗之前获取实体ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆