drlff
drlff

Reputation: 256

Is there a way to access `last_inserted_id` in TypeORM?

Specifically, is there way to access the last_inserted_id in a TypeORM transaction? i.e.:

 try {
        // transaction
        await getManager().transaction(async (trManager): Promise<any> => {

            const company = new Company();
            const savedCompany = await trManager.save(company);
            const companyId = savedCompany.lastInsertedId;

            // ..............more saves..............//

            // await trManager.save(otherEntityUsingCompanyId);

        });
    } catch (err) {
        console.error("err: ", err);         
    }

I've looked through the docs thoroughly (admittedly, perhaps not thoroughly enough if i've missed something) and haven't seen anything. The closest documentation I've found that looks similar is:

const userId = manager.getId(user); // userId === 1

This seems like a common enough use case that I'm assuming I missed something, which is why I've hesitated to file an issue. Any help would be appreciated. Thanks!

Upvotes: 7

Views: 8804

Answers (3)

Janeks Malinovskis
Janeks Malinovskis

Reputation: 570

const companyInsert = new Company({/* set properties */});

const res = await getConnection()
    .getRepository(Company)
    .insert(companyInsert);

const insertedId_option_A = companyInsert.id;
const insertedId_option_B = Number(res.identifiers[0].id);

A) Appears that TypeORM will modify the passed object after inserting into DB. Additionally it will add/fill all properties that was populated by default column values.

B) Extended answer of Willow-Yang.

Tested with MySQL driver and TypeORM 0.2.32

p.s. Not sure about the specific case with Transaction.

Upvotes: 0

drlff
drlff

Reputation: 256

NOTE: Please note that I have not used TypeORM since roughly the time of original answer, so there may be better ways to do this now.

Figured it out. Use returning method...

const inserts = await getConnection()
            .createQueryBuilder()
            .insert()
            .into(Company)
            .values([
                { Name: "abcdef", Address: "456 denny lane" }, 
                { Name: "ghijkil", Address: "899 ihop lane" }
            ])
            .returning("INSERTED.*")
            .printSql()
            .execute();

// `inserts` holds array of inserted objects

Upvotes: 8

Willow Yang
Willow Yang

Reputation: 276

OUTPUT or RETURNING clause only supported by Microsoft SQL Server or PostgreSQL databases.

For MySql, you can get the last_insert_id from the result. it looks like the following.

InsertResult {
  identifiers: [ { id: 1 } ],
  generatedMaps:
   [ { id: 1,
       creationTime: 2019-09-03T10:09:03.000Z,
       lastUpdate: 2019-09-03T10:09:03.000Z } ],
  raw:
   OkPacket {
     fieldCount: 0,
     affectedRows: 1,
     insertId: 1,
     serverStatus: 2,
     warningCount: 0,
     message: '',
     protocol41: true,
     changedRows: 0 } }

Upvotes: 2

Related Questions