问题描述
我在续集中有两张桌子
- 仓库
- 产品项
然后我想创建一个连接表名Inventory(productionItemId,warehouseId,qty)这是我当前的代码:
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",
});
以上代码只创建了一个连接表inventory(productionItemId,warehouseId).我想知道我们如何在库存中添加额外的字段,例如数量等.感谢您的帮助.谢谢
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
推荐答案
引用:
如果你想在你的连接表中添加额外的属性,你可以在定义关联之前在sequelize中为连接表定义一个模型,然后告诉sequelize它应该使用该模型进行连接,而不是创建一个新的:
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 })
要向用户添加新项目并设置其状态,请将额外的 options.through 传递给 setter,其中包含连接表的属性
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' }})
这篇关于如何在连接表“belongsToMany"中添加更多字段在续集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!