Sequelize.js “Sequelize for”中是否有捷径;user.setGroups();当我有所有的组ID时?

Sequelize.js “Sequelize for”中是否有捷径;user.setGroups();当我有所有的组ID时?,sequelize.js,Sequelize.js,在Sequelize中,如果我有一个简单的父子关系,我可以设置foreignKey列而不设置整个对象: Chapter.belongsTo(Book); // this works, but I had to query the DB for the 'book' object return Chapter.create({title: 'The Title'}).then(function(chapter) { return chapter.setBook(book); } 上面生成了

在Sequelize中,如果我有一个简单的父子关系,我可以设置foreignKey列而不设置整个对象:

Chapter.belongsTo(Book);

// this works, but I had to query the DB for the 'book' object
return Chapter.create({title: 'The Title'}).then(function(chapter) {
  return chapter.setBook(book);
}
上面生成了两条SQL语句,一条插入到chapters表中,另一条更新foreignKey

// this also works, if I happen to know the book ID already
return Chapter.create({
   title: 'The Title',
   bookId: 123
})
上面只生成一条SQL语句,用于插入已设置外键的记录

有人知道“类似的速记”在多对多关系中可以做到这一点吗?例如

User.belongsToMany(Group, { through: 'UsersGroup' });
Group.belongsToMany(User, { through: 'UsersGroup' });

return User.create({
  name: 'John Doe',
  groupIds: [ 1, 2, 3 ] // does not work :(
})

哎呀,脑功能紊乱。结果我错过了以下几点:

如果关联模型具有单个主键,则不必将完整对象传递给关联函数:

user.addPicture(req.query.pid)
// Here pid is just an integer, representing the primary key of the picture
因此,我不能在一个调用中创建所有内容(当然,因为我需要插入到另一个表中),但我可以通过调用以下命令来避免额外的查找:

return User.create({name: 'John Doe'}).then(function(user) {
  return user.setGroups([1, 2, 3]);
})

实际上,您可以通过
user.setGroups([1,2,3],{save:false})