2017-06-12 69 views
0

在我的應用程序中,我有兩個不同的表相互關聯的第一個(一對多關係)的ID。應該首先由JSON格式看起來像這樣收集從前端側的數據:節點JS mySQL tripple查詢和信息丟失

cancellation = { 
name: someting 
id: someting 
rule = 
[ 
{someting}, {something}, {something} 
] 
} 

一個表將是取消,第二個的規則。如果我想按照這個順序放置這些信息,我需要先插入一條記錄以取消。然後進行查詢以找出數據庫中此記錄的標識號,並在此之後插入使用此標識符作爲外鍵的所有規則。但是,由於節點JS是異步的,因此在獲取有關記錄程序明星ID的信息以執行代碼的其餘部分之前,將該變量視爲未定義。

app.post('/databaseSend/cancellation', function(req,res){ 
var cancellationReceived = req.body; 
var cancellationID; 
var rules = []; 
var cancellation = []; 
cancellation[0] = 
[ 
    cancellationReceived.name, 
    cancellationReceived.id 
] 
// inserting data into cancellation table 
connection.query("INSERT INTO cancellations (name, User_ID) VALUES ?", [cancellation], 
    function(err,results){ 
     if(err){console.log(err)} 

    } 
) 
//fetching ID of the current record 
connection.query("SELECT id FROM cancellations WHERE User_ID = ? AND name = ?", [cancellationReceived.id, cancellationReceived.name], 
    function(err, results){ 
     var cancellationID = results[0].id; 
    }); 


//assigning ID to use it as a foreign key 
for(var i = 0; i < cancellationReceived.rule.length; i++) 
{ 
    rules[i] = 
    [ 
     cancellationReceived.rule[i].daysBefore, 
     cancellationReceived.rule[i].fee, 
     cancellationReceived.rule[i].type, 
     cancellationID 
    ] 
} 

for(var i = 0; i < rules.length; i++) 
{ 
    console.log(rules[i]); // ID is undefined 
} 

}); 

我該如何解決這個問題?我試圖用setTimeout來暫停我的代碼,但它沒有改變任何東西。

而且我用這個節點模塊針對MySQL - >https://github.com/mysqljs/mysql

回答

1

解決這個問題是RTFM的最好方法。

connection.query('INSERT INTO cancellations (name, user_id) values ?', [cancellation], function(err, results) { 
    if (err) 
     return console.error(err); 

    // See https://github.com/mysqljs/mysql#getting-the-id-of-an-inserted-row 
    var cancellation_id = results.insertId; 

    // Generate sql for rules, join them by ; and execute as one query 
    // See https://github.com/mysqljs/mysql#multiple-statement-queries 
    connection.query(sqls, function(err) { 
     if (err) 
      return console.error(err); 

     // Send response here 
    }); 
})