在bookshelf.js中保存多条记录

4

如何在bookshelf.js中保存多条记录。

如何在不使用循环和插入的情况下保存以下数据。

[
  {name: 'Person1'},
  {name: 'Person2'}
]
4个回答

6

我认为Bookshelf已经更新,用'invokeThen'替换了'invoke'。

var Accounts = bookshelf.Collection.extend({
  model: Account
});
    
var accounts = Accounts.forge([
  {name: 'Person1'},
  {name: 'Person2'}
]) 

accounts.invokeThen('save').then(function() {
  // ... all models in the collection have been saved
});


如何使用where子句在Bookshelf中更新多行数据? - j10
它是一次性保存所有还是逐个保存? - Salar

2

我尝试使用forge并跟随invokeThen,但在我的情况下失败了。看起来我们可以使用模型本身,而无需创建单独的集合实例。这里,Employee是一个模型而不是单独的集合对象。

Employee.collection()
  .add(employees)
  .invokeThen('save');

这对我有用。谢谢。 - JoeyMousepad

2
var Promise = require('bluebird');
var Accounts = bookshelf.Collection.extend({
  model: Account
});

var accounts = Accounts.forge([
  {name: 'Person1'},
  {name: 'Person2'}
])

Promise.all(accounts.invoke('save')).then(function() {
  // collection models should now be saved...
});

请查看评论:Invoke现在已被invokeThen替换。
accounts.invokeThen('save').then(function() {
  // ... all models in the collection have been saved
});

1
认为 invoke 已经被 invokeThen 取代。 - Starchand
10
这并不能一次性保存它们所有。它将为每个保存运行一个单独的数据库查询。 - Asher
@Asher:如何在一个查询中保存所有记录? - j10
为了在一个查询中保存多条记录,您应该使用bookshelf的knex实例,并调用.insert([<items>]) - mark

0
使用如下所示的invokeThen方法中的第三个参数来执行insert方法。
const payload = [{name: 'Person1'},
      {name: 'Person2'}]

Users.collection(payload).invokeThen("save", null, { method: "insert" }).then(result => {
// further logics
})

希望这能有所帮助。

谢谢。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接