我正在编写一个查询,我必须使用 Doctrine 发现表中最后插入的项目的 ID。
我不得不:
$this->getDoctrine()->getConnection()->prepare("SELECT MAX(id) FROM Commit");
我正在编写一个查询,我必须使用 Doctrine 发现表中最后插入的项目的 ID。
我不得不:
$this->getDoctrine()->getConnection()->prepare("SELECT MAX(id) FROM Commit");
当您刷新时,Doctrine 会将实体 id 分配给您的实体。假设您的实体是:
class MyEntity {
protectd $id;
public function getId() {
return $this->id;
}
public function setId($id) {
$this->id = $id;
}
}
当您执行 EntityManager::flush() 时,最后插入的 Id 将分配给 $id 属性。然后您只需执行 $myEntity->getId() 即可获取最后插入的 id。
正如 Cerad 所说,您真的不应该通过执行另一个查询来检索您的实体 ID。相反,您可以让实体管理器使用它在插入时获得的标识符填充(更新)您的实体。一个例子是..
$myEntity = new \Entities\MyEntity();
$myEntity->setProperty($someValue);
// Save my entity ($em = EntityManager)
$em->persist($myEntity);
// Flush my entity manager
try {
$em->flush();
} catch (\Exception $e)
{
}
// Refresh my entity (populate the identifier)
$em->refresh($myEntity);
// Tada
echo $myEntity->getId();
Doctrine 没有任何方法可以做到这一点,flush 仅在最近插入时才有效,并且仅适用于插入它的用户。但是,如果您不想查询该表,因为它很大或因为其他原因,您可以创建另一个表来存储该 ID,并在每次某些用户向该表添加新元素时更新该表。如果你不想那样做,那么你必须按照你说的去做。