2016-05-26 1 views
1

を挿入します。ネストされたレコードは、私たちは以下のようにデータベーススキーマを持ってknex.js

studentsテーブル

| id |名前|アドレス|


学生が複数の教育歴を持っています。

education_historiesテーブル

| id |度|大学| student_id |

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

私はNode.jsKnex.jsに新しいです:#student_idたちは以下のように、クライアント側からJSON構造を取得し、外部キーポインティング学生テーブル


です。私はstudentを挿入し、education historyを入れて、データベースにbluebird約束をKnexで使用したいと思っています。どうすればこの問題を解決できますか?

私は約束以下で試してみました:

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

答えて

2

自分の質問に答えるために申し訳ありませんがしかし、私はどのように私は解決しないことだけを説明したいです。

我々はKnex insert docsを参照して、複数の方法

  1. によってアクションを行うことができ、私達はちょうど配列にJSONオブジェクトを配置して、テーブルに複数のレコードを直接にはめ込むことができます。したがって、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); 
          }) 
         }); 
         }); 
        ); 
    
関連する問題