【发布时间】:2015-05-23 10:01:48
【问题描述】:
我正在为我的 ORM 使用 [BookshelfJS][bookshelfjs] 并且想知道如何访问 though 表上的数据。
我有 3 个模型,Recipe、Ingredient 和 RecipeIngredient,它们连接了这两个模型。
var Recipe = BaseModel.extend({
tableName: 'recipe',
defaults: { name: null },
ingredients: function () {
return this
.belongsToMany('Ingredient')
.through('RecipeIngredient')
.withPivot(['measurement']);
}
}));
var Ingredient = BaseModel.extend({
tableName: 'ingredients',
defaults: { name: null },
recipes: function () {
return this
.belongsToMany('Recipe')
.through('RecipeIngredient');
}
}));
var RecipeIngredient = BaseModel.extend({
tableName: 'recipe_ingredients',
defaults: { measurement: null },
recipe: function () {
return this.belongsToMany('Recipe');
},
ingredient: function () {
return this.belongsToMany('Ingredient');
}
}));
然后我尝试检索Recipe 以及所有Ingredients,但无法弄清楚如何访问RecipeIngredient 上的measurement。
Recipe
.forge({
id: 1
})
.fetch({
withRelated: ['ingredients']
})
.then(function (model) {
console.log(model.toJSON());
})
.catch(function (err) {
console.error(err);
});
返回:
{
"id": 1,
"name": "Delicious Recipe",
"ingredients": [
{
"id": 1,
"name": "Tasty foodstuff",
"_pivot_id": 1,
"_pivot_recipe_id": 1,
"_pivot_ingredient_id": 1
}
]
}
没有measurement 值。
我原以为.withPivot(['measurement']) 方法会获取该值,但它不会返回任何额外数据。
我是否遗漏了什么或误解了它的工作原理?
【问题讨论】:
标签: javascript node.js bookshelf.js