📜  knex last insert id mysql (1)

📅  最后修改于: 2023-12-03 15:32:28.770000             🧑  作者: Mango

Knex.js getLastInsertId() for MySQL

Introduction

When using a relational database system like MySQL, it is often necessary to perform insertions into tables that have auto-incrementing primary keys. Once an insertion is finished, it can be useful to retrieve the ID of the newly created row for further processing. Knex.js provides a convenient way to do this with the getLastInsertId() method, which returns the value of the auto-incrementing column from the insert statement.

Prerequisites
  • Knex.js version 0.14.6 or later
  • MySQL database
Usage

Assuming you already have a Knex.js instance set up and connected to your MySQL database, the getLastInsertId() method can be used as follows:

knex('my_table')
  .insert({ column_name: 'value' })
  .then(() => knex('my_table').select(knex.raw('LAST_INSERT_ID()')))
  .then(rows => console.log(rows[0]['LAST_INSERT_ID()']));

Explanation:

  • The insert() method inserts a new row into the my_table table with a value of value in the column_name column.
  • The then() method is used to chain a subsequent query that selects the last insert ID from the database. In this case, the raw SQL LAST_INSERT_ID() function is used to retrieve the ID.
  • Finally, the then() method is used again to log the obtained ID to the console.

Note that the LAST_INSERT_ID() function is specific to MySQL and may not work with other database systems. Also, the syntax for selecting the last insert ID may vary depending on your version of Knex.js, so make sure to consult the documentation for your particular version.

Conclusion

Retrieving the last insert ID after performing an insertion is a common task when working with relational databases. With Knex.js and MySQL, this can be easily accomplished using the getLastInsertId() method. By following the steps outlined in this guide, you should now have a working example of how to use this method in your own code.