I want to create an entry in a join table using bookshelf. I followed the instructions on the bookshelf website here. (Models instantiation with bookshelf and tables creation with knex).
Is there a way, upon creation of a new Book, to add values to the authors_books table WITHOUT creating an authors_books model/collection?
What should I add to this:
//Books references the Books collection that holds the Book models
var book = new Book({
title: title,
base_url: req.headers.origin
});
book.save().then(function(newBook) {
Books.add(newLink);
res.send(200, newBook);
});
Yes, of course, it's quite simple.
You need two models, Book and Author. Both have
belongsToMany
relationship defined andwithPivot
as well.withPivot
lists the attributes that are in the junction table, see more here: http://bookshelfjs.org/#Model-withPivotAfterwards, you call
updatePivot
, to update the attributes that are inauthor_book
table only.