何时使用 Knex transacting() 与链接 trx 对象
When to use Knex transacting() vs chaining off the trx object
Knex 的交易文档中的代码如下所示:
knex.transaction(function(trx) {
var books = [
{title: 'Canterbury Tales'},
{title: 'Moby Dick'},
{title: 'Hamlet'}
];
return trx
.insert({name: 'Old Books'}, 'id')
.into('catalogues')
.then(function(ids) {
return Promise.map(books, function(book) {
book.catalogue_id = ids[0];
// Some validation could take place here.
return trx.insert(info).into('books');
});
});
})
在这里,我看到函数 transacting()
的广泛使用,示例如下:
knex.transaction(function(trx) {
knex('foo')
.transacting(trx)
.insert({id:"bar", username:"bar"})
// etc
})
Knex 描述 transacting()
的例子与上面类似:
Used by knex.transaction, the transacting method may be chained to any query and passed the object you wish to join the query as part of the transaction for.
我的问题是:
trx.insert().into('foo')
和 knex('foo').transacting(trx).insert()
有什么区别,为什么要用一个而不是另一个?
当你想在同一个事务中执行多个操作时,使用.transacting(trx)
很方便:
knex.transaction(function (trx) {
return Promise.all([
knex('foo').insert({ name: 'My Name' }).transacting(trx),
knex('bar').insert({ field: 'Value' }).transacting(trx)
])
// ---- or something like ----
return Promise.all(SOME_INPUT_VALUES.map(function (value) {
return knex('foo_bar').update('lul', value.lul).where('id', value.id).transacting(trx)
}))
})
不太了解另一种方法的具体用法。这可能只是风格问题。你有两个接口,你可以选择一个你最喜欢的。至于我,我习惯了.transacing(trx)
Knex 的交易文档中的代码如下所示:
knex.transaction(function(trx) {
var books = [
{title: 'Canterbury Tales'},
{title: 'Moby Dick'},
{title: 'Hamlet'}
];
return trx
.insert({name: 'Old Books'}, 'id')
.into('catalogues')
.then(function(ids) {
return Promise.map(books, function(book) {
book.catalogue_id = ids[0];
// Some validation could take place here.
return trx.insert(info).into('books');
});
});
})
在这里,我看到函数 transacting()
的广泛使用,示例如下:
knex.transaction(function(trx) {
knex('foo')
.transacting(trx)
.insert({id:"bar", username:"bar"})
// etc
})
Knex 描述 transacting()
的例子与上面类似:
Used by knex.transaction, the transacting method may be chained to any query and passed the object you wish to join the query as part of the transaction for.
我的问题是:
trx.insert().into('foo')
和 knex('foo').transacting(trx).insert()
有什么区别,为什么要用一个而不是另一个?
当你想在同一个事务中执行多个操作时,使用.transacting(trx)
很方便:
knex.transaction(function (trx) {
return Promise.all([
knex('foo').insert({ name: 'My Name' }).transacting(trx),
knex('bar').insert({ field: 'Value' }).transacting(trx)
])
// ---- or something like ----
return Promise.all(SOME_INPUT_VALUES.map(function (value) {
return knex('foo_bar').update('lul', value.lul).where('id', value.id).transacting(trx)
}))
})
不太了解另一种方法的具体用法。这可能只是风格问题。你有两个接口,你可以选择一个你最喜欢的。至于我,我习惯了.transacing(trx)