Bookshelf.js-如何保存多对多关系? [英] Bookshelf.js - how to save many-to-many relationship?
本文介绍了Bookshelf.js-如何保存多对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在以多对多"关系保存数据时遇到了麻烦.
I'm having troubles saving data in a "many-to-many" relationship.
这是我的模特:
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")?
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!
推荐答案
您要在此处执行的操作是将ID附加到您的关系中,如下所示:
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);
});
});
官方文档中也对此进行了说明: http://bookshelfjs.org/#Model-attach
It is also stated in the official docs: http://bookshelfjs.org/#Model-attach
这篇关于Bookshelf.js-如何保存多对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文