ptk
ptk

Reputation: 7653

What's the difference between knex.into('sometable') and knex('sometable) in Knex?

I started using Knex today and I came across two different ways of using transactions. One contains '.into' and the other doesn't.

Method 1 uses ".into"

Documented here: https://knexjs.org/#Transactions

var Promise = require('bluebird');

// Using trx as a transaction object:
knex.transaction(function(trx) {

  var books = [
    {title: 'Canterbury Tales'},
    {title: 'Moby Dick'},
    {title: 'Hamlet'}
  ];

  knex.insert({name: 'Old Books'}, 'id')
    .into('catalogues') /* INTO USED HERE */
    .transacting(trx)
    .then(function(ids) {
      return Promise.map(books, function(book) {
        book.catalogue_id = ids[0];

        // Some validation could take place here.

        return knex.insert(book).into('books').transacting(trx);
      });
    })
    .then(trx.commit)
    .catch(trx.rollback);
})
.then(function(inserts) {
  console.log(inserts.length + ' new books saved.');
})
.catch(function(error) {
  // If we get here, that means that neither the 'Old Books' catalogues insert,
  // nor any of the books inserts will have taken place.
  console.error(error);
});

Method 2 doesn't use ".into"

Documented here: https://knexjs.org/#Builder-transacting

var Promise = require('bluebird');
knex.transaction(function(trx) {
/* INTO NOT USED HERE */
  knex('books').transacting(trx).insert({name: 'Old Books'})
    .then(function(resp) {
      var id = resp[0];
      return someExternalMethod(id, trx);
    })
    .then(trx.commit)
    .catch(trx.rollback);
})
.then(function(resp) {
  console.log('Transaction complete.');
})
.catch(function(err) {
  console.error(err);
});

Is knex.into('sometable') just syntactic sugar for knex('sometable) or is there a more meaningful difference? Why is it used in one example and not the other?

Upvotes: 0

Views: 180

Answers (1)

Mikael Lepistö
Mikael Lepistö

Reputation: 19728

.into() is just an older alternative syntax for selecting table name. Both works just the same. I use knex('TableName') where ever it is possible.

Upvotes: 1

Related Questions