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

断了今生、忘了曾经 提交于 2019-12-21 08:23:07

问题


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

Here are my models:

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

The challenge is, how to insert IDs that I get in array to the junction table in my database (named "course_people")?

Here's my code so far:

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

Thank you again for your time and suggestions!


回答1:


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



来源:https://stackoverflow.com/questions/28715684/bookshelf-js-how-to-save-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!