如何使用 Bookshelf 访问 `through` table 上的数据

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

我正在为我的 ORM 使用 [BookshelfJS][bookshelfjs],我想知道如何访问 though table.

上的数据

我有 3 个模型,RecipeIngredientRecipeIngredient,两者结合在一起。

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

Return:

{
  "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']) 方法会获取该值,但它不会 return 任何其他数据。

我是否遗漏了什么或误解了它的工作原理?

我不太清楚你为什么要使用 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']);;
  }
}));

不需要 交叉点 table 的附加模型。只需确保在您的数据库中将联结点 table 定义为 ingredients_recipe(按字母顺序连接 tables 的名称!)。或者,您可以向 belongsToMany 函数提供您自己的自定义名称,以便为联结点 table 命名。请务必在 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);
  });