使用 MySQL 在 React/NodeJS/Express 中構建一個簡單的 ToDo 應用程式。用戶加入一個組(代碼中的“家庭”),然后可以通過 familyId 過濾查看任務。要創建任務,我首先有一個從 Users 表中查找用戶的 familyId 的查詢,然后我想將該 familyId 值包含在后續的 INSERT 查詢中以在 Tasks 表中創建任務行。我的 task.model.js 如下:
const sql = require("./db.js");
// constructor
const Task = function(task) {
this.title = task.title;
this.familyId = task.familyId;
this.description = task.description;
this.completed = task.completed;
this.startDate = task.startDate;
this.userId = task.userId;
};
Task.create = (task, result) => {
sql.query("SELECT familyId FROM users WHERE userId = ?", task.userId, (err, res) => {
if (err) {
console.log("Error selecting from USERS: ", err);
return result(err, null);
}
sql.query("INSERT INTO tasks (familyId, title, description, completed, startDate) VALUES (?,?,?,?,?)", [result, task.title, task.description, task.completed, task.startDate], (err, res) => {
if (err) {
console.log("Error inserting in TASKS: ", err);
return result(err, null);
}
})
console.log("created task: ", { id: res.insertId, ...task });
return result(null, { id: res.insertId, ...task });
});
};
但是,我不知道如何正確使用 SELECT 查詢的 familyId 結果作為后續 INSERT 查詢中的引數。我知道整體語法有效,因為我可以手動插入一個 ID 值作為引數并且整個操作成功完成 - 我只需要知道如何在下一個查詢中使用第一個查詢的結果。
uj5u.com熱心網友回復:
您使用它的方式應該有效,但問題是您已將回呼定義為 res 但在第二個 sql 查詢中傳遞結果
sql.query("SELECT familyId FROM users WHERE userId = ?", task.userId, (err, res) => {
if (err) {
console.log("Error selecting from USERS: ", err);
return result(err, null);
}
//res should have the value for the familyId of the given user so in next line pass res not result
sql.query("INSERT INTO tasks (familyId, title, description, completed, startDate) VALUES (?,?,?,?,?)", [res[0].familyId, task.title, task.description, task.completed, task.startDate], (err, res) => {
if (err) {
console.log("Error inserting in TASKS: ", err);
return result(err, null);
}
})
console.log("created task: ", { id: res.insertId, ...task });
return result(null, { id: res.insertId, ...task });
});
uj5u.com熱心網友回復:
SQL 在 result 中回傳陣列,因此使用 result[0] 獲取第一個 Object ,然后通過 result[0].keyName 訪問物件鍵
Task.create = (task, result) => {
sql.query("SELECT familyId FROM users WHERE userId = ?", task.userId, (err, users) => {
if (err) {
console.log("Error selecting from USERS: ", err);
return result(err, null);
}
let familyId = users && users[0] ? users[0].familyId : null;
sql.query("INSERT INTO tasks (familyId, title, description, completed, startDate) VALUES (?,?,?,?,?)", [familyId, task.title, task.description, task.completed, task.startDate], (err, res) => {
if (err) {
console.log("Error inserting in TASKS: ", err);
return result(err, null);
}
})
console.log("created task: ", { id: res.insertId, ...task });
return result(null, { id: res.insertId, ...task });
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/534415.html
標籤:数据库节点.js表示后端
上一篇:CodeIgniter4:如何在發送HTTP請求和接收HTTP回應之間執行MySQL查詢
下一篇:mysql搜索街道和門牌號
