How to add more field in joined table “belongsToMany” in Sequelize?

六眼飞鱼酱① 提交于 2021-01-29 05:53:00

问题


I have two table in sequelize

  1. Warehouse
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!