gpt4 book ai didi

javascript - 如何在 sequelize.js 中正确映射关系的属性?

转载 作者:行者123 更新时间:2023-12-03 22:23:59 25 4
gpt4 key购买 nike

我正在创建一个食谱数据库(通常称为食谱),我需要在其中建立成分和食谱之间的多对多关系,并且我将 结合使用。

当一种成分添加到食谱中时,我需要声明进入食谱的该成分的正确数量。

我已经声明(简化示例)

var Ingredient = sequelize.define('Ingredient', {
name: Sequelize.STRING
}, {
freezeTable: true
});

var Recipe = sequelize.define('Recipe', {
name: Sequelize.STRING
}, {
freezeTable: true
});

var RecipeIngredient = sequelize.define('RecipeIngredient', {
amount: Sequelize.DOUBLE
});

Ingredient.belongsToMany(Recipe, { through: RecipeIngredient });
Recipe.belongsToMany(Ingredient, {
through: RecipeIngredient,
as: 'ingredients'
});

我的问题是当我的 REST 端点执行时如何返回数据
router.get('/recipes', function(req, res) {
Recipe.findAll({
include: [{
model: Ingredient,
as: 'ingredients'
}]
}).then(function(r) {
return res.status(200).json(r[0].toJSON());
})
});

发送到客户端的结果 JSON 如下所示(省略时间戳):
{
"id": 1,
"name": "Carrots",
"ingredients": [
{
"id": 1,
"name": "carrot",
"RecipeIngredient": {
"amount": 12,
"RecipeId": 1,
"IngredientId": 1
}
}
]
}

虽然我想要的只是
{
"id": 1,
"name": "Carrots",
"ingredients": [
{
"id": 1,
"name": "carrot",
"amount": 12,
}
]
}

也就是说,我希望将关系表中的 amount 字段而不是整个 RecipeIngredient 对象包含在结果中。

sequelize 生成的数据库如下所示:
Ingredientsid  name1   carrotRecipesid  name1   CarrotsRecipeIngredientsamount  RecipeId  IngredientId12      1         1

I've tried to provide an attributes array as a property to the include like this:

include: [{
model: Ingredient,
as: 'ingredients',
attributes: []
}]

但是将 ['amount']['RecipeIngredient.amount'] 设置为属性值会引发错误,例如

Unhandled rejection SequelizeDatabaseError: column ingredients.RecipeIngredient.amount does not exist



显然我可以使用 .map 在 JS 中解决这个问题,但肯定有办法让 sequelize 为我做这项工作吗?

最佳答案

您可以使用 sequelize.literal。使用Recipe的Ingredient别名,可以写成如下。我不知道这是否是正确的方法。 :)

[sequelize.literal('`TheAlias->RecipeIngredient`.amount'), 'amount'],

我用 sqlite3 测试过。接收到的别名为“ir”的结果是
{ id: 1,
name: 'Carrots',
created_at: 2018-03-18T04:00:54.478Z,
updated_at: 2018-03-18T04:00:54.478Z,
ir: [ { amount: 10, RecipeIngredient: [Object] } ] }

在此处查看完整代码。

https://github.com/eseom/sequelize-cookbook

关于javascript - 如何在 sequelize.js 中正确映射关系的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34497040/

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