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

标签 node.js orm bookshelf.js

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

这是我的模型:

 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/

相关文章:

node.js - 下载带有环回的文件 4

javascript - Node.js:提交表单时接收空正文

java - JPA Hibernate 类型定义

node.js - 如何在 github 操作的特定文件夹中运行 CI 步骤

php - 在 Laravel Eloquent 中使用 “With()” 函数获取特定列

hibernate - 如何在 Intellij IDEA 的 Hibernate 中使用逆向工程进行 ORM?

mysql - 使用 knex 和 bookshelf 创建数据库和模式的语法?

node.js - Nodejs Bookshelf 中的简单引用关系

sql - 使用 bookshelf js 按相关表列对结果进行排序

java - 我正在尝试在 android 日志中打印或写入 protected file/data/data/com.package/file