Doctrine 2 - 如何在 PostPersist 中获取最后插入的 id 的 ID?

Posted

技术标签:

【中文标题】Doctrine 2 - 如何在 PostPersist 中获取最后插入的 id 的 ID?【英文标题】:Doctrine 2 - How to get the ID of the last inserted id in PostPersist? 【发布时间】:2011-07-06 12:15:39 【问题描述】:

标题说明了一切。我在实体中有一个生命周期回调函数。我想从 PostPersist 事件而不是实体中获取最后插入的 id。作为一个我不想做的例子

$newSeating = new Seat();
$newSeating->setTitle("Something");
$this->_em->persist($newSeating);
$this->_em->flush();
$newSeating->getId();

在文档中是这样写的

postPersist - postPersist 事件 在实体之后发生在实体上 已被持久化。这将是 在数据库插入后调用 操作。生成的主键 值可在 postPersist 事件。

那么如何在 postPersist 中获取主键值呢? (我正在使用 Mappedsuperclass 和 postpersist 函数在 Mappedsuperclass 中,因此它可用于扩展 Mappedsuperclass 的每个实体) 谢谢。

【问题讨论】:

【参考方案1】:
...
public function postPersist(\Doctrine\ORM\Event\LifecycleEventArgs $e) 
    $newSeating = $e->getEntity();
    $id         = $newSeating->getId();

...

【讨论】:

它会抛出 postpersist 需要 1 个参数但给定 0 的错误。 你使用的是哪个 Doctrine 2 版本? 你能显示你的postPersist事件处理程序注册的相关代码吗?

以上是关于Doctrine 2 - 如何在 PostPersist 中获取最后插入的 id 的 ID?的主要内容,如果未能解决你的问题,请参考以下文章