typescripttypeorm

Returning ID of inserted query in TypeORM and MySQL


I,m new to TypeORM and I have problem that I'm trying to solve. I'm wondering how to retrieve ID after INSERT query. I have column @PrimaryGeneratedColumn() with id number in my entity and my code looks similar to this:

await getConnection()
    .createQueryBuilder()
    .insert()
    .into(Test)
    .values([
        { firstName: "test", lastName: "test" }
     ])
    .execute();

What I want to archieve is to return ID of inserted row after executing this function.

EDIT: I'm using MySQL.

Is that possible?

Thanks.


Solution

  • You can add .returning("your_id_column_name")

    await getConnection()
        .createQueryBuilder()
        .insert()
        .into(Test)
        .values([
            { firstName: "test", lastName: "test" }
         ])
        .returning("your_id_column_name")
        .execute();