“user.setGroups()"在 Sequelize 中有快捷方式吗?当我拥有所有组 ID 时? [英] Is there a shortcut in Sequelize for "user.setGroups()" when I have all the group ids?

查看:49
本文介绍了“user.setGroups()"在 Sequelize 中有快捷方式吗?当我拥有所有组 ID 时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);
}

上面生成了两条 SQL 语句,一条是 INSERT 到章节表中,一条是更新外键.

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
})

以上仅生成一条 SQL 语句,该语句使用已设置的外键插入记录.

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 :(
})

推荐答案

糟糕,大脑出现故障.原来我错过了这一点文档:

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]);
})

这篇关于“user.setGroups()"在 Sequelize 中有快捷方式吗?当我拥有所有组 ID 时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆