I am trying to switch from mysql to Zend / TableGateway class.
I wonder if there is a method, similar to mysql_insert_id, to get the autoincremented id of the last inserted row.
Googling around, I found some answers, pointing to the lastInsertId() of the DB-Adapter, however, this method seems no longer available in ZF2. Also: the return value of the insert method is returning a boolean value, not the last id as in ZF1.
Currently I am using a ugly workaround. Please see code below.
Is there a better / recommended way of getting the 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));