我有Comment
模型belongsTo
User
模型。这就是我创建它的方式:
var log_status = console.log;
var u = require("lodash");
models.sequelize.sync({
force: true,
logging: log_status,
}).then(function() {
return models.Users.bulkCreate([
{ first_name: "John", last_name: "Smith" },
{ first_name: "Jane", last_name: "Carter" },
], {logging: log_status});
}).then(function() {
return models.Users.findAll({logging: log_status});
}).then(function(users) {
user_ids = u.object(u.map(users, function (x){
return [x.first_name + " " x.last_name, x.id];
}));
return models.Comment.bulkCreate([
{ UserId: user_ids["John Smith"], body: "This is a comment" },
{ UserId: user_ids["John Smith"], body: "This is another comment" },
{ UserId: user_ids["Jane Carter"], body: "This is my comment" },
], {logging: log_status});
}).then(function(comments) {
comment_ids = u.object(u.map(comments, function (x){
return [x.first_name + " " x.last_name, x.id];
}));
// ...
});
因为我使用sqlite作为我的数据库,所以我必须使用findAll
来获取ID,因为only PostgreSQL and MySQL return the primary ids after bulkCreate
。这有效,但我想知道是否有更好的方法来填充相关模型。