Skip to content Skip to sidebar Skip to footer

How To Access Data On A `through` Table With Bookshelf

I am using [BookshelfJS][bookshelfjs] for my ORM and am wondering how to access data on a though table. I have 3 Models, Recipe, Ingredient and RecipeIngredient which joins the two

Solution 1:

I'm not exactly sure why you want to use through. If it's just a basic many-to-many mapping, you can achieve this by doing the following:

varRecipe = BaseModel.extend({
  tableName: 'recipe',

  defaults: { name: null },

  ingredients: function () {
    returnthis
      .belongsToMany('Ingredient').withPivot(['measurement']);
  }
}));

varIngredient = BaseModel.extend({
  tableName: 'ingredients',

  defaults: { name: null },

  recipes: function () {
    returnthis
      .belongsToMany('Recipe').withPivot(['measurement']);;
  }
}));

You don't need an additional model for junction table. Just be sure to define a junction table in your database as ingredients_recipe (alphabetically joining the name of tables!). Or , you can provide your own custom name to belongsToMany function for what the junction table should be named. Be sure to have ingredients_id and recipe_id in ingredients_recipe

This is pretty much it. Then you can do

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

Post a Comment for "How To Access Data On A `through` Table With Bookshelf"