在Sequelize> = 1.7
we can use promises
你能为我解释一下如何从这个代码中获取每个用户的价值:@H_404_3@
var User = sequelize.define("user",{ username: Sequelize.STRING }) User .sync({ force: true }) .then(function() { return User.create({ username: 'John' }) }) .then(function(john) { return User.create({ username: 'Jane' }) }) .then(function(jane) { return User.create({ username: 'Pete' }) }) .then(function(pete) { console.log("we just created 3 users :)") console.log("this is pete:") console.log(pete.values) // what i want: console.log("this is jane:") console.log(jane.values) console.log("this is john:") console.log(john.values) })
UPD@H_404_3@
所有值需要与其他模型的集合关联.
其实我需要一些像这样的代码:@H_404_3@
User.hasMany(Group) Group.hasMany(User) User .sync({ force: true }) .then(function() { return User.create({ username: 'John' }) }) .then(function(john) { return User.create({ username: 'Jane' }) }) .then(function(jane) { return User.create({ username: 'Pete' }) }) .then(function(pete) { return Group.findOrCreate({id: 1}) }) .then(function(group) {return group.setUsers([john,jane,pete])}) .then(function(result) { console.log(result)}) })
解决方法
蓝鸟的方式是
collection helper functions.
User.sync({ force: true }) .then(function() { return Promise.map( ['John','Jane','Pete'],function(name) { return User.create({ username: name }); }) }).spread(function(john,pete) { console.log("we just created 3 users :)") console.log("this is john:") console.log(john.values) console.log("this is jane:") console.log(jane.values) console.log("this is pete:") console.log(pete.values) })
如果您需要连续创建它们,请将其更改为mapSeries
(3.0).@H_404_3@
如果数组不需要是动态的,而您只需要像在示例中一样通过承诺链传递共享值,请查看How do I access previous promise results in a .then() chain?.@H_404_3@