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