Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knex does not return insert Id

This is my table(CELLID) structure.

+---------+------------+------+-----+---------+-------+
| Field   | Type       | Null | Key | Default | Extra |
+---------+------------+------+-----+---------+-------+
| CELL_ID | int(11)    | NO   | PRI | NULL    |       |
| STATUS  | tinyint(4) | NO   |     | NULL    |       |
+---------+------------+------+-----+---------+-------+

And this is my code to insert into the table.

knex('CELLID').insert(insertObj)
    .then(function (result) {
      _log.info(reqContainer.uuid, "Successfully Added To CELLID||", result)
      // respond back to request
      _log.info(reqContainer.uuid, "Exiting CELLID_S");
      return resolve(result)  // respond back to request
    })
    .catch(function (err) {

      _log.error(reqContainer.uuid, "Failed Adding To CELLID ||", err)
      _log.error(reqContainer.uuid, "Exiting CELLID_S");
      // respond back to request
      return reject(Error("Failed Adding CELLID"));
    })

After a successful insert, the Id has to be returned.This does not happen in my case. I always get and Id of 0 on an insert.

I had tried by adding an extra column, auto-increment primary key ID(removing CELL_ID as PK).In this case, I get the ID(auto-increment value).

What am I missing here?

Thanks.

like image 240
sanjith kumar Avatar asked Apr 18 '17 06:04

sanjith kumar


2 Answers

You have to pass second argument to the insert method, which specifies a column to retrieve a value from.

In your case it should look like this:

knex('CELLID').insert(insertObj, 'CELL_ID')
    .then(function (result) {
        // ...
    })
like image 158
reidar13 Avatar answered Oct 07 '22 14:10

reidar13


MySQL doesn't support returning, so it's not available through Knex.

Here is a list of supported DB's from the Knex docs: http://knexjs.org/#Builder-returning

This is the only other method that I'm aware of to get the last inserted row: How to get the ID of INSERTed row in mysql?

like image 40
Luke Bailey Avatar answered Oct 07 '22 15:10

Luke Bailey