I have array of object at raw Postman. and i want that insert to my table. i have confusion to make the controller and model. this is my code
postman My postman image
My controller code:
module.exports = {
postOrder: async (request, response) => {
try {
const setData = {
// id_history : request.body,
id_product : request.body.orders.id_product,
product_name : request.body.orders.product_name,
image : request.body.orders.image,
ppn : request.body.orders.ppn,
price : request.body.orders.price
}
const result = await postOrder(setData)
return helper.response(response, 201, "Create Category Success", result);
} catch (error) {
return helper.response(response, 400, "Bad Request", error);
}
}
}
My model code:
module.exports = {
postOrder: (setData) => {
return new Promise((resolve, reject) => {
connection.query("INSERT INTO order SET ?", setData, (error, result) => {
console.log(result)
if(!error) {
const newResult = {
...setData
}
resolve(newResult)
} else {
reject(new Error(error))
}
})
})
}
}
I'm sorry if the explanation is not clear. please let me know if the explanation is not clear
I would tend to lean towards building the query with placeholders and then passing in the values, it may work your way but I'm not sure it would be a prepared query.
module.exports = {
postOrder: setData => new Promise((resolve, reject) => {
let keys = Object.keys(setData)
let values = Object.values(setData)
let sql = `
INSERT INTO order (
${keys.join(',')}
) VALUES (
${keys.fill('?', 0, keys.length).join(',')}
)
`
connection.query(sql, values, (error, result) => {
if (error) reject(new Error(error))
resolve(orderData)
})
})
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.