javascript - 如何在 SequelizeJS 中设置创建时通过模型的额外属性?
问题描述
我的模型:
Recipe (id, name)
Ingredient (id, name)
Recipe_Ingredient (recipeId, ingredientId, quantity)
我的联想:
Recipe.belongsToMany(Ingredient, { through: Recipe_Ingredient })
Ingredient.belongsToMany(Recipe, { through: Recipe_Ingredient })
我的问题:
如何创建包含一些成分和附加数量的食谱?
我试过:
Recipe.create({
name: 'Pizza',
ingredients:[
{
name: 'mozarella',
recipe_ingredients: {
quantity: 5
}
}
]
}, {
include:[Ingredient]
})
为配方、成分和配方_成分创建记录。唯一的问题是数量的值不是从数据源收集的。
解决方案
我找到了一个解决方案,灵感来自 pedro here 的答案(How do I ORM additional columns on a join table in sequelize?),并通过改变视角给出。
receipe (name:string)
ingredient (quantity:int)
type (name: string)
receipe.hasMany(ingredient, {as:'ingredients'} )
ingredient.belongsTo(type)
然后我可以使用这样的数据:
receipe.create({
name: 'Pizza',
ingredients:[
{
quantity: 5,
type: {
name: 'ingredient 1'
}
}, {
quantity: 6,
type: {
name: 'ingredient 2'
}
} {
quantity: 5,
type_id: 1
}]
}, {
include:[{
model; ingredient,
as: 'ingredients',
include:[{
model: type
}]
}]
})
它有一些缺点,但对我来说已经足够了。
一个问题可能是,如果您添加两个相同新类型的项目,您将获得唯一键冲突(因为类型是唯一的,并且 sequelize 在尝试创建它之前不会尝试搜索该类型是否存在)。
另一个问题是,如果您只在数据中指定 type_id,它实际上不会返回结果中该类型所引用的类型。
推荐阅读
- node.js - Sinon 在 NodeJS 控制器中模拟 Promise.all
- dynamic - 如何在雪花中以动态值为中心
- rust - 调用 take 后如何继续使用迭代器?
- python - 如何获取包含值的 Sqlite3 列名?
- android-studio - Android中带有占位符/提示文本的纯文本框
- google-cloud-data-fusion - Cloud Data Fusion 如何决定将哪个项目网络用于 dataproc 资源?
- php - 更改数组数组的索引名称
- javascript - RegExp 在数组中查找值
- javascript - 文件夹路径 - 绝对文件夹路径
- sql - 合并两个匹配值的查询结果