Vahid Alimohamadi
Vahid Alimohamadi

Reputation: 5858

Sequelize insert additional fields into junction table

as described in sequelize documentation here,

Foo.belongsToMany(Bar, { through: Baz }) then there is a method to insert into junction table:

fooInstance.addBars([5,4])

It will insert into Baz junction table two fields: FooId,BarId. But i need to insert another field value too. sth like this:

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

How i can achieve that without manual insert?

Upvotes: 1

Views: 1824

Answers (1)

Anatoly
Anatoly

Reputation: 22758

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

Upvotes: 2

Related Questions