Bookshelf.js - how to save many-to-many relationship?

前端 未结 1 1245
半阙折子戏
半阙折子戏 2021-02-20 06:51

I\'m having troubles saving data in a \"many-to-many\" relationship.

Here are my models:

 var CoursePeople = bookshelf.Model.extend({
     tableName: \'c         


        
相关标签:
1条回答
  • 2021-02-20 07:05

    What you want to do here is attach the ids to your relation, like this:

    app.post('/users/', function(req, 
      console.log(req.body);
      var courses_ids = req.body.courses_ids; //array of ids
      delete req.body.courses_ids;
      new User(req.body).save()
        .then(function(user){
         // this is important
          return user.courses().attach(courses_ids);
        }).catch(function(error){
           console.log(error);
        });
    });
    

    It is also stated in the official docs: http://bookshelfjs.org/#Model-attach

    0 讨论(0)
提交回复
热议问题