Simple POST endpoint to create a customer record and also a customer address record with associated foreign key
// create: customer and associated address record
app.post("/", (req, res) => {
// Customer rec
let insertCustomer = "INSERT INTO Customers (Name) VALUES(?)";
const customerValues = [req.body.name];
insertCustomer = mysql.format(insertCustomer, customerValues);
connection.query(insertCustomer, function(err, result, fields) {
if (err) throw err;
// get ID of customer record
const customerID = result.insertId;
// Customer_Address rec
let insertCustomerAddress =
"INSERT INTO Customer_Addresses (Customer_ID, Street_Address, Postal_Code, Country) VALUES(?,?,?,?)";
const customerAddress = [
customerID,
req.body.street_address,
req.body.postal_code,
req.body.country
];
insertCustomerAddress = mysql.format(
insertCustomerAddress,
customerAddress
);
connection.query(insertCustomerAddress, function(err, result, fields) {
if (err) throw err;
let customerID = result.insertId;
});
res.send("User Created successfully");
});
});
ID |
Name |
1 |
Ryan |
2 |
Jonathan |
3 |
Colin |
4 |
Syed |
ID |
Customer_ID(FK) |
Street_Address |
Postal_Code |
Country |
1 |
2 |
123 Big Walk Way |
75023 |
US |
2 |
3 |
509 Charter Road |
90021 |
US |
3 |
1 |
999 Night Stalker Road |
12345 |
US |