Skip to content

InsertReturningFeature

Alexey Savchuk edited this page Oct 20, 2013 · 3 revisions

Important!

InsertReturningFeature moved to new repo ZF2PgSQL.

Include InsertReturningFeature to your TableGateway

$tableGateway = new TableGateway(
    'album',
    $dbAdapter,
    array(
        /* More features... */
        new \ZendExtensions\Db\TableGateway\Feature\InsertReturningFeature
    ),
    $resultSetPrototype
);

Prepare your Insert request

class AlbumTable
{
    /* More methods... */

    public function saveAlbum(Album $album)
    {
        $data = array(
            'artist' => $album->artist,
            'title'  => $album->title,
        );

        $id = (int)$album->id;
        if ($id == 0) {
            $this->tableGateway->insert($data);
            $insert = new \ZendExtensions\Db\Sql\Insert($this->tableGateway->getTable());
            $insert->values($data);
            $insert->returningColumns(array('id'));
            $this->tableGateway->insertWith($insert);
            $results = $this->tableGateway->getFeatureSet()
                ->getFeatureByClassName('\ZendExtensions\Db\TableGateway\Feature\InsertReturningFeature')
        	->getReturning();
            // You returning id
            $id = $results['id'];
        } else {
            if ($this->getAlbum($id)) {
                $this->tableGateway->update($data, array('id' => $id));
            } else {
                throw new \Exception('Form id does not exist');
            }
        }
    }
}

Clone this wiki locally