用knex.js插入嵌套logging

我们有一个数据库模式如下:

students

| id | 名字| 地址|

一个学生有多个教育历史。

education_histories

| id | 度| 大学| student_id | student_id是指向学生表的外键

我们从客户端获得JSON结构,如下所示:

 { "name" :"Ram Neupane", "address": "Kathmandu, Bagmati", "education_histories": [ { "degree": "I.Sc.", "university": "Tribhuvan University" }, { "degree": "BE", "university": "Tribhuvan University" } ] } 

我是Node.js和Knex.js的新手 。 我想用Knex的蓝鸟承诺在数据库中插入student和嵌套的education history 。 我怎么解决这个问题。

我已经尝试了以下诺言:

 function create (jsonParam) { return new Promise(function (resolve, reject) { knex('students') .insert({name: jsonParam.name, address: jsonParam.address}) .returning('id') .then(function (response) { # Here, I want to insert record to education_histories table }) .catch(function (err) { reject(err); }); }) } 

对不起回答我自己的问题但是我只想解释一下,我该如何解决。

我们可以通过多种方式来做这件事

  1. 参考Knex插入文档 ,我们可以通过将json对象放在数组中直接插入多个logging。 所以,我们有jsonParam['education_histories']这是一个包含education_history json对象的数组。

      var student_id = response[0]; var educationHistoryParams = jsonParam['education_histories']; educationHistoryParams.forEach(function(educationHistory){ educationHistory.student_id = student_id; }); knex('education_histories').insert(educationHistoryParams) .then(resolve()); 
  2. 另一种方法是使用Bluebird Promise.join API或Bluebird Promise.map API 。

      var student_id = response[0]; var educationHistoryParams = jsonParam['education_histories']; return Promise.join( educationHistoryParams.forEach(function (educationHistory) { educationHistory.student_id = student_id; new Promise(function (resolve, reject) { knex('education_histories').insert(educationHistory) .then(resolve()) .catch(function (err) { reject(err); }) }); }); );