2017-08-24 15 views
1

これは私が達成しようとしているものです。私はnode.jsサーバーから返されたJSONデータを最初のmysqlクエリ(配列JSONデータ)の値に基づいて結合したいと思っていますnodejsでpromiseを使って2つのmysqlクエリを実行するには?

私はちょうどmultipleStatements可能にする2つのMySQLクエリ:真は、コードは次のようになり:

app.post( '/製品'、関数(REQ、RES){

connection.query('call getProductList; call rowCountTotal', function (err, rows, fields) { 
    if (!err) { 
     var response = []; 

     if (rows.length != 0) { 
      response.push({ 'result': 'success', 'data': rows }); 
     } else { 
      response.push({ 'result': 'error', 'msg': 'No Results Found' }); 
     } 

     res.setHeader('Content-Type', 'application/json'); 
     res.status(200).send(JSON.stringify(response)); 
    } else { 
     res.status(400).send(err); 
    } 
}); 

})。

データが2列に分離された2つのJSONを示したでしょうが、私はここで構築したいことは1 JSONはこのように見えている複数のアレイJSONデータ、であるより:私が欲しい

サンプルJSON :

[ 
    { 
     "product_id":"1", 
     "product_name":"MX-001", 
     "product_attachment":[ 
     { 
      "product_id":"1", 
      "product_attachment_id":"1", 
      "file_name":"maxgrand5.jpg", 
      "file_path":"assets" 
     } 
     ] 
    } 
] 

そして、ここで私は私がここで

Promise.all (i think this code i should use right?) : 

    return new Promise(function(resolve, reject) { 

     Promise.all(connection.query('call getProductSingle("'+ product_series +'")', function (err, rows, fields) { 
      if (!err) { 
       var response = []; 

       if (rows.length != 0) { 
        response.push({ 'result': 'success', 'data': rows }); 
       } else { 
        response.push({ 'result': 'error', 'msg': 'No Results Found' }); 
       } 

       connection.query('call getProductAttachment("'+ rows[0][0].product_id +'")', function (err, rowsAttachment, fields) { 
        if (!err) { 
         console.log("second query"); 
         if (rowsAttachment.length != 0) { 
          response.push({'product_attachment': rowsAttachment }); 
         } else { 
          response.push({ 'result': 'error', 'msg': 'No Results Found' }); 
         } 
        } 
       }); 
       console.log("outside second query"); 
       res.setHeader('Content-Type', 'application/json'); 
       res.status(200).send(JSON.stringify(response)); 
      } else { 
       res.status(400).send(err); 
      } 

      console.log("last"); 
      if (err) { 
       return reject(err); 
      } 
      resolve(res); 
     })); 
    }); 

を使用しようと、私のNode.jsサーバー側のコードでやろうとすることで名前の私のストアドプロシージャの結果であります'getProductSingle':

  1. のproduct_id = 1
  2. PRODUCT_NAME = MX-001

、ここでは私の2番目の手順の結果 'getProductAttachment' です:

  1. のproduct_id = 1
  2. file_name = maxgrand5.jpg
  3. file_path = assets
  4. product_attachment_id = 1

1つのPRODUCT_IDは、データが加わっどのように私が得ることができる1以上が

をproduct_attachment_id持つことができますか?

私はちょうど私の質問を更新しました、問題は2番目のクエリは、私がリクエストをするには遅すぎる、私はそれを行う方法を遅くするために約束を使用する必要がありますか?

SELECT ps.product_id, ps.product_name, pa.product_attachment_id, 
pa.file_name, pa.file_path 
FROM product_single ps 
LEFT JOIN product_attachment pa 
ON ps.product_id = pa.product_id 
ORDER by ps.product_id,pa.product_attachment_id; 

次で:

+0

あなたは必要な結果を返すクエリを作成する必要があります(保存機能付きの可能性があります)。 –

+0

@ UsagiMiyamotoは、関数を保存するとJSONのようなツリーを作成できますそれ?しかし、私はpromise.allを読むことができる –

+0

@ UsagiMiyamotoこんにちは私は約束について私の質問を更新 –

答えて

1

まず私はproduct_singleテーブルはproduct_attachmentsに結合されているクエリを作成し、多分あなたはWHERE句またはLIMITOFFSETとページングメカニズムとそれを制限したいですコードcall product_join_attでこのクエリを参照します。

return new Promise(function(resolve, reject) { 
    var result_products = []; 
    var result_attachments = []; 
    var old_id = undefined; 
    var old_name = undefined; 
    var new_id = undefined; 
    var row_index = 0; 
    connection.query('call product_join_att', function (err, rows, fields) { 
     if (err) { 
      reject(err); 
      return; 
     } else if (rows.length == 0) { 
      reject(new Error('No Results found')); 
      return; 
     } 
     while (row_index < rows.length ) { 
      new_id = rows[row_index].product_id; 
      if (old_id !== new_id) { // any new line with an new id... 
       if (typeof old_id !== 'undefined') { // when the old line is existing 
        result_products.push(// push the product 
         {"product_id": old_id.toString(), 
         "product_name":old_name, 
         "product_attachment": result_attachments 
         }); 
       } 
       old_id = new_id; // remember the new_id 
       old_name = rows[row_index].product_name;// and name 
       product_attachments = []; // and initialize attachments. 
      } 
      product_attachments.push({ // provide the inner attachment informations. 
       "product_id": new_id, 
       "product_attachment_id" : rows[row_index].product_attachment_id, 
       "file_name" : rows[row_index].file_name; 
       "file_path" : rows[row_index].file_path; 
      }); 
      row_index++; // and go to the next row. 
     } 
     if (typeof old_id !== 'undefined') { // if there are still data 
      result_products.push(// push the last line also. 
       {"product_id": old_id.toString(), 
       "product_name":old_name, 
       "product_attachment": result_attachments 
       }); 
     } 
    } // query 
    resolve(result_products); 
} // end of promise... 
+0

ありがとうございます@Myonara私は約束の方法なしでそれを行うことができると思う、私は下で動作する私のコードを持っているが、私は約束の方法でJSON配列ツリーを行うように頼んでいるので、そんなに –

0

私はsimplier溶液でそれを把握することが、この方法は、それを成し遂げるために「約束」の方法ではありませんので、皆さんはこのような問題に直面した場合、使用することを決定。私は一次元JSON配列で、ループにただ一つのルート配列JSONを多くのデータを必要といけないので、私はちょうどこのようにそれを置く:

app.post('/getsingleproduct', function (req, res) { 
    var product_series = req.body.product_series; 

    connection.query('call getProductSingle("'+ product_series +'")', function (err, rows, fields) { 
     if (!err) { 
      var response = []; 

      if (rows.length != 0) { 
       response.push({ 'result': 'success', 'data': rows[0] }); 
      } else { 
       response.push({ 'result': 'error', 'msg': 'No Results Found' }); 
      } 

      connection.query('call getProductAttachment("'+ rows[0][0].product_id +'")', function (err, rowsAttachment, fields) { 
       if (!err) { 

        if (rowsAttachment.length != 0) { 

         response[0].data[0]['product_attachment']= rowsAttachment[0]; 

         res.setHeader('Content-Type', 'application/json'); 
         res.status(200).send(JSON.stringify(response)); 
        } else { 
         response.push({ 'result': 'error', 'msg': 'No Results Found' }); 
         res.status(400).send(err); 
        } 
       } 
      }); 

     } else { 
      res.status(400).send(err); 
     } 
    }); 

}); 

これは非約束の方法です、あなたが道を約束する必要がある場合は、 @Myonaraの答えを探して、私は最高だと思います

関連する問題