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

时间:2015-02-25 09:43:20

标签: node.js orm bookshelf.js

我很难在多对多的情况下保存数据"关系。

以下是我的模特:

 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")?

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

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

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

1 个答案:

答案 0 :(得分:14)

您要在此处执行的操作是将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