Question

Does anyone know what's the best way to insert a HABTM rule into the database using sequelize js?

My tables are users <-- user_books --> books. So Books can have multiple users and a user can have multiple books. Now if I want to insert a new book into the database I use:

User.find(query).complete(function(err,source){
      var data = {
        book: req.body.book,
      };
      Book
        .create(data)
});

This works well to insert a new book for an existing user. But the user_books table stays empty. Even though I created an UserBooks model:

Was it helpful?

Solution

The code you posted shows nothing about a UserBooks model?

You can do two things:

Create the book and associate it with user:

Book.create(data).then(function (book) {
  source.addBook(book)
});

or In a single step:

source.createBook(data).then(function (book) {

});

Have a look at https://github.com/sequelize/sequelize/wiki/API-Reference-Associations

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top