Sequelize 将附加字段插入连接 table

Sequelize insert additional fields into junction table

sequelize 文档 here

中所述

Foo.belongsToMany(Bar, { through: Baz }) 然后有一种方法可以插入到连接点 table:

fooInstance.addBars([5,4])

它将插入到 Baz 结点 table 两个字段:FooId,BarId。 但我也需要插入另一个字段值。像这样的东西:

fooInstance.addBars([{BarId: 5, otherField:'xxx'}, ...]

如何在不手动插入的情况下实现这一点?

Advanced Many-to-Many guide

const User_Profile = sequelize.define('User_Profile', {
  selfGranted: DataTypes.BOOLEAN
}, { timestamps: false });
User.belongsToMany(Profile, { through: User_Profile });
Profile.belongsToMany(User, { through: User_Profile });

With this, we can now track an extra information at the through table, namely the selfGranted boolean. For example, when calling the user.addProfile() we can pass values for the extra columns using the through option.

Example:

const amidala = await User.create({ username: 'p4dm3', points: 1000 });
const queen = await Profile.create({ name: 'Queen' });
await amidala.addProfile(queen, { through: { selfGranted: false } });