lastInsertId在Postgresql中不起作用

时间:2012-05-08 04:30:43

标签: php postgresql pdo lastinsertid

我正在使用Postgresql,当我想使用PDO检索最新的插入ID时,我遇到了问题。这是我的代码:

$db->lastInsertId('columnName');

错误消息显示

SQLSTATE[42P01]: Undefined table: 7 ERROR: relation "columnName" does not exist

我想我对PHP手册中的“序列对象”有一些误解。

Note:

Returns the ID of the last inserted row, or the last value from a sequence object, 
depending on the underlying driver. For example, PDO_PGSQL() requires you to specify the 
name of a sequence object for the name parameter.

目前,“columnName”是该自动递增属性的字符串。任何人都可以指出我哪里出错了吗?感谢。

4 个答案:

答案 0 :(得分:16)

PostgreSQL使用sequences生成serial列的值,而serial列通常用于PostgreSQL中的“自动递增”列。序列具有名称,并且通常独立于任何特定表,因此您可以使用一个序列为多个不同的表生成唯一ID;序列名称是lastInsertId想要的参数:

  

例如, PDO_PGSQL()要求您为 名称 参数指定序列对象的名称。

PostgreSQL创建的序列对象自动命名为[table]_[column]_seq,所以:

$id = $db->lastInsertId('tableName_columnName_seq');

答案 1 :(得分:3)

我今天遇到了这个问题,lastInsertId()只返回false。找到了解决我的问题的答案:https://stackoverflow.com/a/31638196/1477123

CREATE TABLE ingredients (
    id         SERIAL PRIMARY KEY,
    name       varchar(255) NOT NULL,
);

因此序列名称将为ingredients_id_seq

$db->lastInsertId('ingredients_id_seq');

答案 2 :(得分:1)

因此序列名称将为ingredients_id_seq

$db->lastInsertId('ingredients_id_seq');

这种格式实际上解决了我的问题!!!

答案 3 :(得分:-1)

使用序列名称代替列名称

$db->lastInsertId('columnName');