data-api-client
data-api-client copied to clipboard
Get insertID of multiple queries of a transaction
Is there a way to retrieve r.InsertID of multiple queries inside a following query? The following code will demonstrate my use case:
db.transaction()
.query(insertContactSQL, formData.sender)
.query(insertContactSQL, formData.receiver)
.query(insertContactSQL, formData.customer)
.query(insertOrderSQL, {
senderID: INSERT_ID_OF_FIRST_QUERY,
receiverID: INSERT_ID_OF_SECOND_QUERY,
customerID: INSERT_ID_OF_THIRD_QUERY,
});
I haven't done this with InsertID, but I have done it using the SQL RETURNING syntax which PostgreSQL offers. Not sure if MySQL does.
For instance if insertContactSQL were something like the below, assuming that my_table has an autogenerated id column,
"INSERT INTO my_table (name, phone_number) VALUES (:name, :phone) RETURNING id"
...then you should be able to do this...
db.transaction()
.query(insertContactSQL, formData.sender)
.query(insertContactSQL, formData.receiver)
.query(insertContactSQL, formData.customer)
.query((prevResult:any) =>
{
return [insertOrderSQL, {
senderID: prevResult.records[0].id,
receiverID: prevResult.records[1].id,
customerID: prevResult.records[2].id,
} ];
});