data-api-client icon indicating copy to clipboard operation
data-api-client copied to clipboard

Get insertID of multiple queries of a transaction

Open mg98 opened this issue 5 years ago • 1 comments

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,
        });

mg98 avatar Sep 24 '20 11:09 mg98

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,
                 } ];
          });

marracuene avatar Jun 11 '21 21:06 marracuene