Is there a shortcut in Sequelize for “user.setGroups()” when I have all the group ids?

╄→гoц情女王★ 提交于 2019-12-25 04:24:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!