【问题标题】:Sequelize Self Relationship with junction table用联结表续集自我关系
【发布时间】:2020-03-31 21:58:30
【问题描述】:

我想建立一个表示:An item is composed by a specific amount of others items 的续集关系。

数据库表

Item (itemId, name)
Ingredient (ingredientId, itemParentId, itemChildrenId, amount)

序列化模型

// Item.js
class Item extends Sequelize.Model { }
Item.init({
  itemId: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  name: Sequelize.STRING,
}, {
  sequelize: db,
})

// Ingredient.js
class Ingredient extends Sequelize.Model { }
Ingredient.init({
  ingredientId: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  amount: Sequelize.INTEGER,
}, {
  sequelize: db,
})

我只是想编写正确的 sequelize 关联以匹配我的数据库逻辑,所以我尝试了:

// Association.js
Item.belongsToMany(Item, { through: Ingredient, as: 'ingredients', foreignKey: 'itemParentId' })

但是我遇到了这个错误Unknown column 'ingredients->ingredient.ingredientItemId' in 'field list',这是真的,但我不知道如何指定正确的键/列。

请帮忙!

【问题讨论】:

    标签: javascript node.js sequelize.js


    【解决方案1】:

    我发现几个问题:首先,您在成分模型中执行 Item.init。可能是你的一个错误。将其更改为 Ingredient.init。(我个人从未使用过这个“init” api,我对模型的定义不同,所以我不确定它是如何工作的)

    其次,将 Ingredient 和 Item 的主键都改为“id”,例如:

    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
      }
    

    另外,您的关联不正确,需要通过联结表:

    Item.belongsToMany(Ingredient, { through: "ItemIngredient"})
    

    请注意,此处的“通过”指的是一个表名,如果您使用 model.sync(),Sequelize 将自动创建它,如果不是 - 您将需要自己创建它(或使用迁移,我推荐),列:itemId、componentId。

    您还需要添加“反向”关联,如下所示:

    Ingredient.belongsToMany(Item, { through: "ItemIngredient"})
    

    【讨论】:

    • 对于Item.init 2次,只是复制错误,我只是编辑它。而且我不确定您是否理解问题,我不需要表 ItemIngredient 因为成分是 Item 和自身之间的连接表。
    • 我没有使用through 而是使用Item.hasMany(Ingredient, { ... }) 两次使用不同的键(itemParentIditemChildrenId)解决了我的问题。
    • 啊,不是多对多,更像是一对多
    猜你喜欢
    • 2019-08-08
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 2019-02-12
    • 1970-01-01
    相关资源
    最近更新 更多