kuldeep.kamboj
kuldeep.kamboj

Reputation: 2606

In ZF2, Getting last insert id after insertion without using TableGateway

I need last insert id after executing a insert statement. Now I am not using TableGateway so $this->lastInsertValue is not available to me. What other options are available if I need to use Insert statement through Sql Object not a Table Gateway Object.

$objInsert = new Insert('name_master');
$objInsert->values(array( 'username' => $name,
                'price' => 0,
                'is_approval_needed' => 'n'
             ));

$sql = new Sql($this->adapter);

$result = $sql->prepareStatementForSqlObject($objInsert)->execute()->getAffectedRows();

As I need to execute multiple insert statements in different tables using last insert id of previous insert, Now I want to do it in a single method of my Model.

Upvotes: 4

Views: 10287

Answers (2)

S B
S B

Reputation: 1363

$dbAdapter = $this->tableGateway->adapter;
$lastId = $dbAdapter->getDriver()->getConnection()->getLastGeneratedValue();

Upvotes: 1

Crisp
Crisp

Reputation: 11447

The Zend\Db\Adapter\Driver\DriverInterface specifies a getLastGeneratedValue() method, so presumably this should work...

 $lastId = $this->adapter->getDriver()->getLastGeneratedValue();

Upvotes: 14

Related Questions