获取 Postgresql 的最后插入 id [英] Get last insert id of Postgresql
问题描述
根据问题:
他们已经说过,检索最后一个插入 ID 的最佳方法是:
they have stated that the best way to retrieve the last insert id is:
INSERT INTO ....
RETURNING id;
我想为 Postgresql 创建一个包装类,以便在我运行时,例如:
I want to create a wrapper class for Postgresql so that when i run, for example:
$id = $db_wrapper->insert("INSERT...");
它总是返回插入到变量 $id
中的最后一个 id.我不知道将传递给 insert()
函数的查询的 auto_inc 列名称,我不想在末尾添加 "RETURNING id"
在我所有的插入查询中 - 关于如何实现这一点的任何想法?
that it will always return the last id inserted into variable $id
. I do not know the auto_inc column name for queries that will be passed to the insert()
function and I would prefer not to have to add "RETURNING id"
to the end of all my insert queries - any ideas on how to achieve this?
推荐答案
PostgreSQL 将(默认情况下)创建一个名为user_id_seq"的序列.例如,如果您的表名是 user
.那么它是 user_id_seq
PostgreSQL will (by default) create a sequence called 'user_id_seq'. for example if your table name is user
. then it is user_id_seq
然后您可以执行以下操作:
You can then do something like:
$strTable = "user";
$last_insert_id = $objPDO->lastInsertId("$strTable_id_seq");
查看多用户安全方法http://www.postgresql.org/docs/9.0/interactive/functions-sequence.html
查看其他方式mysql_insert_id 替代 postgresql
EDIT:根据 Eli
//if your table name in model is **user**
$strTable = "user";
$model = new User();
// do your stuff
$model->save();
$last_insert_id = $model->lastInsertId("$strTable_id_seq");
或
如果您的模型名为 Model,并且有一个名为 id(也就是表的 PK)的属性,那么您可以通过以下方式访问:
If your model is called Model, and has a property called id (aka, the PK of the table), then you can acces this way:
//...
$model = new Model();
// do your stuff....
$model->save();
$the_id = $model->id;
这篇关于获取 Postgresql 的最后插入 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!