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

偶尔善良 提交于 2019-12-02 09:49:24

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:

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

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);
  });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!