问题
In Sequelize, if I have a simple parent-child relationship I can set the foreignKey column without the whole object:
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);
}
The above generates two SQL statements, one to INSERT into the chapters table and one to UPDATE the foreignKey.
// this also works, if I happen to know the book ID already
return Chapter.create({
   title: 'The Title',
   bookId: 123
})
The above generates only one SQL statement that INSERTs the record with the foreign key already set.
Does anyone know of a "similar shorthand" to do that with many-to-many relations? E.g.
User.belongsToMany(Group, { through: 'UsersGroup' });
Group.belongsToMany(User, { through: 'UsersGroup' });
return User.create({
  name: 'John Doe',
  groupIds: [ 1, 2, 3 ] // does not work :(
})
    回答1:
Oops, brain malfunction. Turns out that I missed this bit of documentation:
You don't have to pass in a complete object to the association functions, if your associated model has a single primary key:
user.addPicture(req.query.pid) // Here pid is just an integer, representing the primary key of the picture
So, I can't create everything in one call (of course, since I need to insert into another table), but I can avoid extra lookups by calling:
return User.create({name: 'John Doe'}).then(function(user) {
  return user.setGroups([1, 2, 3]);
})
    来源:https://stackoverflow.com/questions/28751483/is-there-a-shortcut-in-sequelize-for-user-setgroups-when-i-have-all-the-grou