Bookshelf.js - 如何保存多对多关系?

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

我在 "many-to-many" 关系中保存数据时遇到问题。

这是我的模型:

 var CoursePeople = bookshelf.Model.extend({
     tableName: 'course_people'
 });

 var Course = bookshelf.Model.extend({
     tableName: 'course',
     users: function(){
         return this.belongsToMany(User);
     }
 });

 var City = bookshelf.Model.extend({
     tableName: 'city',
     users: function(){
         return this.hasMany(User);
     }
 });

 var User = bookshelf.Model.extend({
   tableName: 'people',
   city: function(){
     return this.belongsTo(City);
   },
   courses: function(){
     return this.belongsToMany(Course);
   }
 });

挑战在于,如何将我在数组中获得的 ID 插入到我的数据库(名为 "course_people")中的结点 table?

到目前为止,这是我的代码:

 app.post('/users/', function(req, res) {
         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){
         console.log(user.id);
         //How to store the ids in the junction table?

     }).catch(function(error){
         console.log(error);
     });
 });

再次感谢您的宝贵时间和建议!

您在这里要做的是将 ID 附加到您的关系中,如下所示:

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

官方文档中也有说明:http://bookshelfjs.org/#Model-attach