Hayk Manasyan
Hayk Manasyan

Reputation: 506

Zend Framework 2 PostgreSQL lastInsertValue returns null

I have code for inserting data to table. Here is my code:

public function createPage(Pages $page)
    {
        $data = array(
            'page_name' => $page->page_name,
            'parent_page_id' => $page->parent_page_id,
            'category' => $page->category,
            'create_date' => $page->create_date,
        );

        try {
           $id = $this->tableGateway->insert($data);
           $id = $this->tableGateway->lastInsertValue;
        } catch (Exception $ex) {
            throw new Exception($ex->getMessage());
        }

        return $id;
    }

When I use MySql, I've got the row's id, but with PostgreSQL I've got null.

Upvotes: 1

Views: 597

Answers (1)

peterpeterson
peterpeterson

Reputation: 1325

Yes,

$id = $this->tableGateway->getAdapter()->getDriver()->getLastGeneratedValue("sequence_name");

Or

$id = $this->tableGateway->getAdapter()->getConnection()->getLastGeneratedValue

Depending on what zf2 version you have.

However, there is some difference between Postgresql and MySql using the native php PDO class, which zf2 wraps and provide the tableGateway.

With native php PDO you may need to do something like:

"INSERT INTO tbl_table (table_name) values ('foo') RETURNING table_id;"

Upvotes: 2

Related Questions