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

后端 未结 1 642
攒了一身酷
攒了一身酷 2021-01-26 03:29

I am using [BookshelfJS][bookshelfjs] for my ORM and am wondering how to access data on a though table.

I have 3 Models, Recipe, Ingredie

相关标签:
1条回答
  • 2021-01-26 04:03

    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);
      });
    
    0 讨论(0)
提交回复
热议问题