let con = mysql.createConnection({
host: "localhost",
user: "root",
password: process.env.PASSWORD,
database: "test_schema"
});
con.connect(function(err) {
if (err) throw err;
let insertPosts = "INSERT INTO posts (title, user_name) VALUES ('제목1', '홍길동')";
//query는 비동기 함수이기 때문에 콜백 함수의 내부에서 쿼리문을 작성한다.
con.query(insertPosts, function (err, result) {
if (err) throw err;
let postId = result.insertId
let params = [
[postId, "댓글1"],
[postId, "댓글2"],
[postId, "댓글3"],
];
//post_id는 posts테이블의 id PK를 참조하는 FK
let insertComments = `INSERT INTO comments (post_id, contents) VALUES ?`;
con.query(insertComments, [params], function (err, result) {
console.log(result)
/*
OkPacket {
fieldCount: 0,
affectedRows: 3,
insertId: 1,
serverStatus: 2,
warningCount: 0,
message: '&Records: 3 Duplicates: 0 Warnings: 0',
protocol41: true,
changedRows: 0
}
*/
})
});
});
posts 테이블
comments 테이블