MySQL에서 Zend/TableGateway 클래스로 전환하려고합니다.Zend/ZF2/TableGateway mysql_insert_id를 대체 하시겠습니까?
마지막으로 삽입 된 행의 자동 증가 ID를 얻기 위해 mysql_insert_id와 유사한 메소드가 있는지 궁금합니다.
주위를 돌아 다니면서 DB 어댑터의 lastInsertId()를 가리키는 답변을 찾았지만이 방법은 ZF2에서 더 이상 사용할 수없는 것 같습니다. 또한 : insert 메소드의 반환 값이 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));
을 실행할 때이 속성을 설정을 얻을 수있는 마법의 재산
$tableGateway->lastInsertValue
도있다 그것은 주목할 필요가 접근 자 " LastInsertValue() "같은 값을 반환합니다. 사용하는 가치가 있으므로 응답을 조롱하고 수업을 더 테스트 할 수있게 만들 수 있습니다. – Dan