问题
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