2

我有这样的事情:

$stmt = $this->getDoctrine()->getConnection()->prepare(
        'insert into someTable (columnList) values (parameters);');

/* 
bind parameters
*/

$stmt->execute();

如何获取最后插入的 ID?

谢谢,斯科特

4

2 回答 2

9

您需要使用 lastInsertId()。

例子:

$dbh = Doctrine_Manager::getInstance()->getCurrentConnection();
$sth = $dbh->prepare("INSERT INTO continent (created_at, updated_at) VALUES ( NOW(), NOW() )");
$sth->execute();

$conn = Doctrine_Manager::getInstance()->getCurrentConnection();
$conn->lastInsertId('continent_id');
于 2012-08-20T19:13:43.267 回答
2

下面的代码正确回答了这个问题:

//This call will get the doctrine connection from inside a symfony2 controller
$conn = $this->getDoctrine()->getConnection();
$stmt = $conn->prepare(
        'insert into someTable (columnList) values (parameters);');

/* 
bind parameters
*/

$stmt->execute();
$id = $conn->lastInsertId();

要从您创建的学说存储库类中获取连接:

$conn = $this->getEntityManager()->getConnection();
于 2016-01-02T07:01:07.967 回答