获取 Postgresql 的最后插入 id

编程入门 行业动态 更新时间:2024-10-25 20:28:34
本文介绍了获取 Postgresql 的最后插入 id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

根据问题:

PHP Postgres:获取上次插入 ID

他们已经说过,检索最后一个插入 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");

查看多用户安全方法www.postgresql/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

本文发布于:2023-10-13 20:40:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1489015.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Postgresql   id

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!