Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 712
uglycode Avatar asked Feb 25 '15 09:02

uglycode


1 Answers

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

like image 87
Johannes Lumpe Avatar answered Sep 22 '22 05:09

Johannes Lumpe