gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:16:04 25 4
gpt4 key购买 nike

我在以“多对多”关系保存数据时遇到问题。

这是我的模型:

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

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

最佳答案

你想要在这里做的是将 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);
});
});

官方文档中也有说明:https://bookshelfjs.org/api.html#Collection-instance-attach

关于node.js - Bookshelf.js - 如何保存多对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28715684/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com