Knex中的knex.into('sometable')和knex('sometable)有什么区别?

时间:2018-12-03 04:35:33

标签: sql node.js knex.js

我今天开始使用Knex,遇到了两种使用事务的不同方式。一个包含“ .into”,另一个不包含。

方法1使用“ .into”

此处记录: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);
});

方法2不使用“ .into”

此处记录: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);
});

knex.into('sometable')只是knex('sometable'的语法糖)还是有更有意义的区别?为什么在一个示例中而不是其他示例中使用它?

1 个答案:

答案 0 :(得分:1)

.into()只是选择表名的一种较旧的替代语法。两者的工作原理相同。我尽可能使用knex('TableName')