问题
I have two table in sequelize
- Warehouse
- ProductItem
Then I want to create a joined table name Inventory(productionItemId, warehouseId, qty) and Here is my current code:
Warehouse.belongsToMany(ProductItem, {
as: "productItems",
through: "inventories",
});
ProductItem.belongsToMany(models.Warehouse, {
as: "warehouses",
through: "inventories",
});
The above code only create a joined table inventories(productionItemId,warehouseId). I would like to know how we can add extra field in inventories such as qty and so on. Appreciated for your help. Thank you
回答1:
See BelongsToMany in the official doc
Quote:
If you want additional attributes in your join table, you can define a model for the join table in sequelize, before you define the association, and then tell sequelize that it should use that model for joining, instead of creating a new one:
class User extends Model {}
User.init({}, { sequelize, modelName: 'user' })
class Project extends Model {}
Project.init({}, { sequelize, modelName: 'project' })
class UserProjects extends Model {}
UserProjects.init({
status: DataTypes.STRING
}, { sequelize, modelName: 'userProjects' })
User.belongsToMany(Project, { through: UserProjects })
Project.belongsToMany(User, { through: UserProjects })
To add a new project to a user and set its status, you pass extra options.through to the setter, which contains the attributes for the join table
user.addProject(project, { through: { status: 'started' }})
来源:https://stackoverflow.com/questions/61605988/how-to-add-more-field-in-joined-table-belongstomany-in-sequelize