gpt4 book ai didi

javascript - 使用连接表续写 self 关系

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

我想建立一个代表 An item is composed by a specific amount of others items 的 Sequelize 关系。

数据库表

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

Sequelize 模型
// 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' ,这是真的,但我不知道如何指定正确的键/列。

任何帮助,请!

最佳答案

我看到的问题很少:首先,您在 Ingredient 模型中执行 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,成分Id。

您还需要添加“反向”关联,如下所示:
Ingredient.belongsToMany(Item, { through: "ItemIngredient"})

关于javascript - 使用连接表续写 self 关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60950923/

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