question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to do multiple inserts

See original GitHub issue

This is kind of a noob question, I’m used to using ORMs and decided to go closer to the metal with Knex.

I’m trying to do multiple inserts where the 2nd insert relies on the id of the 1st insert.

Something like this:

    knex("users")
        .insert({ first_name: "John", last_name: "Doe" })
        .exec(function (err, id) {
            knex("groups")
                .insert({ name: "Cool Group" })
                .exec(function (err, id) {
                    // handle results
                });
        });

I might be missing something by not knowing how to use Promises or Transactions properly, but I’d appreciate some help on this very simple problem.

Thanks!

Issue Analytics

  • State:closed
  • Created 9 years ago
  • Comments:17 (11 by maintainers)

github_iconTop GitHub Comments

28reactions
bendruckercommented, Apr 22, 2014

With transactions:

return knex.transaction(function (t) {
  return knex("users")
    .transacting(t)
    .insert({ first_name: "John", last_name: "Doe" })
    .then(function (response) {
      return knex('groups')
        .transacting(t)
        .insert({name: 'Cool Group', user_id: response.id})
    })
    .then(t.commit)
    .catch(t.rollback)
})
.then(function () {
  // transaction suceeded, data written
})
.catch(function () {
  // transaction failed, data rolled back
});
8reactions
mouhannad-shcommented, Aug 2, 2019

For anyone on the internet who comes across this issue like I did

you can read this SO answer.

Basically in your up or down handler you need to return a promise so technically you could do something like:

exports.up = function(knex) {
  const columns = ['column_1', 'column_2', 'column_3'];
  const tables = ['table_1', 'table_2'];
  return Promise.all(
    tables
      .map(table =>
        columns.map(col =>
          knex(table)
            .where(col, '=', 'Wrong value')
            .update({ [col]: 'Corrected value' })
        )
      )
      .flat()
  );
};
Read more comments on GitHub >

github_iconTop Results From Across the Web

SQL Server INSERT Multiple Rows Into a Table Using One ...
To insert multiple rows returned from a SELECT statement, you use the INSERT INTO SELECT statement. SQL Server INSERT multiple rows – examples....
Read more >
Inserting multiple rows in a single SQL query? - Stack Overflow
INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists ...
Read more >
SQL Query to Insert Multiple Rows - GeeksforGeeks
In this article, we see how to insert individual as well as multiple rows in a database using the INSERT statement in the...
Read more >
How to INSERT Multiple Records in SQL - DigitalOcean
SQL INSERT query inserts data into the columns of a particular table. The normal SQL INSERT query inputs the data values in a...
Read more >
How to Insert Multiple Rows in SQL - Database Star
If you have your data in another table and want to insert it into a new table, you can use an INSERT statement...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found