我正在創建食譜數據庫(通常稱爲食譜),我需要在配料和食譜之間具有多對多關係,並且我正在使用sequelize.js與postgresql的組合。如何在sequelize.js中正確映射關係的屬性?
當配料添加到配方中時,我需要聲明進入配方的配料的正確量。
我已經聲明(例如減少)
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,
}
]
}
即,我希望被包括在結果,而不是整個RecipeIngredient
對象從關係表的amount
字段。
通過sequelize生成的數據庫看起來是這樣的:
Ingredients id name 1 carrot Recipes id name 1 Carrots RecipeIngredients amount RecipeId IngredientId 12 1 1
我試圖提供一個attributes
數組作爲財產的include
這樣的:
include: [{
model: Ingredient,
as: 'ingredients',
attributes: []
}]
但無論設置或['amount']
['RecipeIngredient.amount']
作爲屬性值拋出錯誤,如
Unhandled rejection SequelizeDatabaseError: column ingredients.RecipeIngredient.amount does not exist
很明顯,我可以使用.map
在JS中修復這個問題,但是肯定有一種方法可以爲我做續集工作嗎?