我想从mysql切换到Zend/TableGateway类。Zend/ZF2/TableGateway mysql_insert_id替换?
我想知道是否有类似于mysql_insert_id的方法来获取最后一个插入行的自动增量ID。
使用谷歌搜索,我找到了一些答案,指向DB适配器的lastInsertId(),但是,这种方法似乎不再在ZF2中可用。 另外:插入方法的返回值返回一个布尔值,而不是ZF1中的最后一个ID。
目前我正在使用丑陋的解决方法。请参阅下面的代码。
是否有更好的/推荐的方式获取Id?
table_1 {
id: integer, primary key, autoincremented
content: text
}
table_2 {
table_1_id: integer
other_content: text
}
// using mysql
$sql = "INSERT INTO table_1 (content) VALUES ('some text')";
$result = mysql_query($sql);
// check omitted
$id = mysql_insert_id();
$sql = "INSERT INTO table_2 (table_1_id, other_content) VALUES ($id, 'other text')";
$result = mysql_query($sql);
// using Zend - this is the code, I am currently using
//*************************************************************
// get_last_insert_id emulation; works only if content is unique
private function getLastInsertId($tableGateway, $content) {
$entries = $tableGateway->select(array('content' => $content));
foreach ($entries as $entry) {
return $entry->id;
}
return null;
}
// another option: get highest ID, must be the last inserted
private function getLastInsertId($tableGateway) {
// needs a method like 'getRowWithHighestId'
}
//*************************************************************
// ...
table_1_entry = new Table1Entry('some text');
$tableGateway->insert($hydrator->extract($table_1_entry));
//*************************************************************
// using the workaround:
$id = getLastInsertId($tableGateway, $table_1_entry->content);
//
// there MUST be some Zend method to get this last id.
//*************************************************************
table_1_entry = new Table1Entry('other text', $id);
$tableGateway->insert($hydrator->extract($table_2_entry));
时,该属性设置值得一提的还有还有一个访问者“得到LastInsertValue()“返回相同的值。值得使用,所以你可以嘲笑反应,让你的课更加可测试。 – Dan