Zend framework2 Zend/ZF2/TableGateway mysql\u插入\u id替换?
我正在尝试从mysql切换到Zend/TableGateway类 我想知道是否有一种类似于mysql_insert_id的方法来获取最后一个插入行的自动递增id 通过谷歌搜索,我找到了一些答案,指向DB适配器的lastInsertId(),然而,这个方法在ZF2中似乎不再可用。 另外:insert方法的返回值返回的是布尔值,而不是ZF1中的最后一个id 目前我正在使用一个丑陋的变通方法。请参阅下面的代码 是否有更好的/推荐的获取Id的方法Zend framework2 Zend/ZF2/TableGateway mysql\u插入\u id替换?,zend-framework2,zend-db,lastinsertid,last-insert-id,tablegateway,Zend Framework2,Zend Db,Lastinsertid,Last Insert Id,Tablegateway,我正在尝试从mysql切换到Zend/TableGateway类 我想知道是否有一种类似于mysql_insert_id的方法来获取最后一个插入行的自动递增id 通过谷歌搜索,我找到了一些答案,指向DB适配器的lastInsertId(),然而,这个方法在ZF2中似乎不再可用。 另外:insert方法的返回值返回的是布尔值,而不是ZF1中的最后一个id 目前我正在使用一个丑陋的变通方法。请参阅下面的代码 是否有更好的/推荐的获取Id的方法 table_1 { id: integer, p
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));
使用magic属性
$tableGateway->lastInsertValue
获取Id
$id = $tableGateway->lastInsertValue;
此属性是在执行插入数据时设置的
值得注意的是,还有一个访问器“getLastInsertValue()”返回相同的值。值得使用,以便您可以模拟响应并使您的类更易于测试。
$this->lastInsertValue = $this->adapter->getDriver()->getConnection()->getLastGeneratedValue();
`enter code here `$data_add=array(
'line_1' => $Data1->line_1,
'line_2' => $Data1->line_2,
'line_3' => $Data1->line_3,
'city_id' => $Data1->city_id,
'state_id' => $Data1->state_id,
'country_id' => 1,
'is_active' => '1',
);
$adapter = $this->tableGateway->getAdapter();
$otherTable = new TableGateway('address', $adapter);
$otherTable->insert($data_add);
$lastInsertValue= $adapter->getDriver()->getConnection()->getLastGeneratedValue();
print_r('lastInsertId1 :'.$lastInsertValue);
error_log($lastInsertValue);
die();