Javascript 如何访问带有书架的“直通”表上的数据
我正在使用[BookshelfJS][BookshelfJS]进行ORM,我想知道如何通过Javascript 如何访问带有书架的“直通”表上的数据,javascript,node.js,bookshelf.js,Javascript,Node.js,Bookshelf.js,我正在使用[BookshelfJS][BookshelfJS]进行ORM,我想知道如何通过表访问上的数据 我有三种型号,Recipe,配料和RecipeingCredit,它们将两者结合在一起 var Recipe = BaseModel.extend({ tableName: 'recipe', defaults: { name: null }, ingredients: function () { return this .belongsToMany('I
表访问上的数据
我有三种型号,Recipe
,配料
和RecipeingCredit
,它们将两者结合在一起
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');
}
}));
然后,我尝试检索配方
以及所有成分
,但无法确定如何访问RecipeingCredit上的测量
Recipe
.forge({
id: 1
})
.fetch({
withRelated: ['ingredients']
})
.then(function (model) {
console.log(model.toJSON());
})
.catch(function (err) {
console.error(err);
});
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
}
]
}
无测量值
值
我原以为.withPivot(['measurement'])
方法会获取该值,但它不会返回任何附加数据
我是否遗漏了什么或误解了它的工作原理?我不太清楚您为什么要通过
使用。如果这只是一个基本的多对多映射,则可以通过执行以下操作来实现:
var Recipe = BaseModel.extend({
tableName: 'recipe',
defaults: { name: null },
ingredients: function () {
return this
.belongsToMany('Ingredient').withPivot(['measurement']);
}
}));
var Ingredient = BaseModel.extend({
tableName: 'ingredients',
defaults: { name: null },
recipes: function () {
return this
.belongsToMany('Recipe').withPivot(['measurement']);;
}
}));
连接表不需要其他模型。只需确保将数据库中的连接表定义为配料\u配方
(按字母顺序连接表名!)。或者,您可以为belongtomany
函数提供自己的自定义名称,以确定连接表的名称。确保在配料配方中有配料id
和配方id
差不多就是这样。那你就可以了
我不太清楚您为什么要通过
使用。如果这只是一个基本的多对多映射,则可以通过执行以下操作来实现:
var Recipe = BaseModel.extend({
tableName: 'recipe',
defaults: { name: null },
ingredients: function () {
return this
.belongsToMany('Ingredient').withPivot(['measurement']);
}
}));
var Ingredient = BaseModel.extend({
tableName: 'ingredients',
defaults: { name: null },
recipes: function () {
return this
.belongsToMany('Recipe').withPivot(['measurement']);;
}
}));
连接表不需要其他模型。只需确保将数据库中的连接表定义为配料\u配方
(按字母顺序连接表名!)。或者,您可以为belongtomany
函数提供自己的自定义名称,以确定连接表的名称。确保在配料配方中有配料id
和配方id
差不多就是这样。那你就可以了