gpt4 book ai didi

sequelize.js - 如何在 Sequelize 的连接表 "belongsToMany"中添加更多字段?

转载 作者:行者123 更新时间:2023-12-03 22:35:20 24 4
gpt4 key购买 nike

我在 Sequelize 中有两张 table

  • 仓库
  • 产品项

  • 然后我想创建一个连接表名称 Inventory(productionItemId,warehouseId, qty)
    这是我当前的代码:
    Warehouse.belongsToMany(ProductItem, {
    as: "productItems",
    through: "inventories",
    });

    ProductItem.belongsToMany(models.Warehouse, {
    as: "warehouses",
    through: "inventories",
    });

    上面的代码只创建了一个连接表inventory(productionItemId,warehouseId)。我想知道我们如何在库存中添加额外的字段,例如数量等。
    感谢您的帮助。
    谢谢

    最佳答案

    BelongsToMany in the official doc

    引用:

    如果你想在你的连接表中添加额外的属性,你可以在定义关联之前在 sequelize 中为连接表定义一个模型,然后告诉 sequelize 它应该使用该模型进行连接,而不是创建一个新的模型:

    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,其中包含连接表的属性
    user.addProject(project, { through: { status: 'started' }})

    关于sequelize.js - 如何在 Sequelize 的连接表 "belongsToMany"中添加更多字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61605988/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com