简体   繁体   中英

How to interact with a join table in bookshelf and knex?

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 and withPivot as well. withPivot lists the attributes that are in the junction table, see more here: http://bookshelfjs.org/#Model-withPivot

Afterwards, you call updatePivot , to update the attributes that are in author_book table only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM