如何使用Bookshelf访问“通过”表上的数据

How to access data on a `through` table with Bookshelf

本文关键字:数据 通过 何使用 Bookshelf 访问      更新时间:2023-09-26

我正在使用[BookshelfJS][BookshelfJS]作为我的ORM,我想知道如何访问though表上的数据。

我有3个模型,Recipe, IngredientRecipeIngredient连接两者。

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'])方法会抓取值,但它不返回任何额外的数据。

我错过了什么或误解了这是如何工作的?

我不太确定你为什么要使用through。如果它只是一个基本的多对多映射,您可以通过执行以下操作来实现:

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']);;
  }
}));

你不需要一个额外的连接表模型。只要确保在数据库中定义一个连接表为ingredients_recipe(按字母顺序连接表名!)。或者,您可以为belongsToMany函数提供您自己的自定义名称,以确定连接表的名称。确保ingredients_recipe

中有ingredients_idrecipe_id

差不多就是这样了。然后你可以输入

Recipe
  .forge({
    id: 1
  })
  .fetch({
    withRelated: ['ingredients']
  })
  .then(function (model) {
    console.log(model.toJSON());
  })
  .catch(function (err) {
    console.error(err);
  });