2013-04-09 10 views
15

mi sono bloccato con ottenere ultimo inserto id con Zend Framework 2 e ho rinunciato a questo ...ZF2 Come ottenere il valore dell'ID dell'ultimo inserto?

combinazioni ci sono provato:

var_dump($this->tableGateway->insert($insert)); 
var_dump($this->tableGateway->lastInsertValue); 
var_dump($this->tableGateway->getLastInsertValue()); 
var_dump($this->tableGateway->getAdapter()->getDriver()->getConnection()->getLastGeneratedValue()); 

valore è l'inserimento al tavolo, ma ogni riga (eccetto prima, che dà int "1") restituisce null. Per favore non dirmelo, che un framework così grande non dà la possibilità di ottenere l'ultimo valore di inserimento !?

+0

Prova '$ this-> tableGateway-> getAdap ter() -> lastInsertId(); ' – phpisuber01

+0

Errore irreversibile: chiamata al metodo non definito Zend \ Db \ Adapter \ Adapter :: lastInsertId() – Piotr

+0

Hmmm ...' $ this-> lastInsertValue; 'or' $ this-> tableGateway -> lastInsertValue; "L'unica cosa a cui riesco a pensare. – phpisuber01

risposta

4

In Postgres è necessario l'installazione SequenceFeature:

... 
use Zend\Db\TableGateway\Feature; 
... 
public function setDbAdapter(Adapter $adapter) { 
    ... 
    $this->featureSet = new Feature\FeatureSet(); 
    $this->featureSet->addFeature(new Feature\SequenceFeature('YOUR_FIELD_NAME','YOUR_SEQUENCE_NAME')); 
    $this->initialize(); 
} 

Ora $this->tableGateway->getLastInsertValue(); dovrebbe funzionare.

+0

Il libro Zend Framework 2.0 di esempio nella guida per principianti afferma getLastInsertValue() Restituisce il primo valore di inserimento per la chiave primaria delle tabelle. Il tipo restituito è un numero intero. – Julian

26

Ecco quello che io uso:

$data = array()// Your data to be saved; 
$this->tableGateway->insert($data); 
$id = $this->tableGateway->lastInsertValue; 
+0

Ho appena provato questo e funziona perfettamente. –

1

In App\Model\AlbumTable che si estende AbstractTableGateway ottengo ultima id da $inserted_id = $this->lastInsertValue;

come esempio:

if ($id == 0) { 
      $this->insert($data); 
      $inserted_id = $this->lastInsertValue;  
     } elseif ($this->getAlbum($id)) { 
      $this->update(
       $data, array(
       'id' => $id, 
       ) 
      ); 
     } else { 
      throw new \Exception('Form id does not exist'); 
     } 
4

Ok, so che la questione è di pochi mesi, anche se può essere utile per coloro che cercano una soluzione a questo problema per ottenere gli ultimi valori degli inserti il ​​modo migliore è quello di ottenere il valore dall'interfaccia dell'adattatore

do your insert //then 
$id = $adapter->getDriver()->getLastGeneratedValue(); 

questo ha funzionato bene per me per il database mysql

+0

MIGLIORE RISPOSTA +1 e anche +1 sulle altre risposte. – YumYumYum

6

So che questo era un po 'indietro, ma dopo aver trascorso un sacco di tempo su questo particolare problema che ho voluto pubblicare la soluzione per Googler future con lo stesso problema.

Il problema è il driver PGSQL richiede un nome della sequenza per restituire l'ultimo ID come questo:

$adapter->getDriver()->getLastGeneratedValue("sequence_name"); 

Questo funziona in 2.3.1. C'era un bug in 2.2.2 (e forse più tardi) dove il nome non era un parametro del getLastGeneratedValue nel driver, quindi dovresti chiamare direttamente la connessione.

$adapter->getDriver()->getConnection()->getLastGeneratedValue 

Quindi questo è quello che ho trovato guardando attraverso il codice. La soluzione migliore è quella di assicurarsi di aver ZF2 aggiornato, e utilizzare

$adapter->getDriver()->getLastGeneratedValue("sequence_name"); 
+2

Questa è l'unica soluzione che ho trovato che funzionasse per me. – Programmer

0

C'è un'altra possibilità di aggiungere featureset a TableGateway.

In Module.php si può definire (tabella utente per esempio)

  'UserTableGateway' => function ($sm) { 
       $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 
       $resultSetPrototype = new ResultSet(); 
       $resultSetPrototype->setArrayObjectPrototype(new UserEntity()); 
       return new TableGateway('user', $dbAdapter, new Feature\SequenceFeature('user','user_id_seq'), $resultSetPrototype); 

ma c'è un bug in SequenceFeature. Tutto è ok, quando usi lo schema pubblico. Quando devi usare altri schemi dovresti usare Zend \ Db \ Sql \ TableIdentifier;

In questo caso Modulo.php dovrebbe essere:

  'UserTableGateway' => function ($sm) { 
       $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter'); 
       $resultSetPrototype = new ResultSet(); 
       $resultSetPrototype->setArrayObjectPrototype(new UserEntity()); 
       return new TableGateway(new TableIdentifier('user','someSchema'), $dbAdapter, new Feature\SequenceFeature(new TableIdentifier('user','someSchema'),'user_id_seq'), $resultSetPrototype); 

In questo caso sarà un errore con PostgreSQL query SELECT NEXTVAL, perché Caratteristica \ SequenceFeature utilizzerà schema pubblico, invece di definito nel primo argomento per la preparazione di query

SELEZIONA NEXTVAL ('user_id_seq ')

In questa query SQL caso dovrebbe essere

SELEZIONA nEXTVAL (' someSchema'. 'user_id_seq')