mysql - Kohana DB 插入前最后一次插入 ID

标签 mysql kohana-3 kohana-orm

我有一个带有自动增量ID的表。

我必须根据插入之前的id生成序列我可以找到最高的ID值,但是如果之前有删除,并且自动增量

表!= max(id)+1

最佳答案

将其分为两个查询。

  1. 运行插入查询来检索 ID。

  2. 根据检索到的 ID 创建序列。

  3. 使用更新查询将序列值添加到记录中。

使用 ORM 模块的示例代码

$my_table = ORM::factory('Mytable');

$my_table->field1 = 'Value1';
$my_table->field2 = 'Value2';

$my_table->save(); // inserts record

// Create serials (will obviously be more complex than this)  
$my_table->serial = $my_table->id;

$my_table->save(); // updates record

使用数据库模块的示例代码

list($id) = DB::insert('my_table', array('field1','field2'))  
->values(array('value1','value2')  
->execute();

// Create serials (will obviously be more complex than this)  
$serial = $id;

DB::update('my_table')  
->set(array('serial' => $serial))  
->where('id', '=', $id);

关于mysql - Kohana DB 插入前最后一次插入 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21880322/

相关文章:

php - Kohana 3.2,ORM has_many,belongs_to 关系未引用正确的键

php - 是什么导致我的 SQL 事务在 php 没有注意到的情况下中止?

kohana-3 - 帮助 Kohana 3 ORM 加快一点速度

php - Kohana 准备好的语句或查询构建?

php - 数据库异常[1146]: Table 'database.roles' doesn't exist [ SHOW FULL COLUMNS FROM `roles` ]

mysql - SQL返回错误: Unknown column "g" in 'field list'

html - MySQL 更新查询以从所有 "description"字段中删除特定的 Html 标记

mysql - #错误: Cant connect to MySQl server on '192.168.0.114' ((10060) MySQL error code 2003

php - AJAX/JQUERY 不更新 MySQL 行

kohana-3 - 将 Auth 与 ORM 驱动程序 kohana 3.3.0 一起使用时出错