【问题标题】:How to access data on a `through` table with Bookshelf如何使用 Bookshelf 访问“通过”表上的数据
【发布时间】:2015-05-23 10:01:48
【问题描述】:

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

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

返回:

{
  "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


    【解决方案1】:

    我不确定您为什么要使用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);
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-28
      • 2012-09-19
      • 1970-01-01
      相关资源
      最近更新 更多