Returning ID of inserted query in TypeORM and MySQL

12,748

Solution 1

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();

Solution 2

Try this

let test: Test = [{ firstName: "test", lastName: "test" }];
test = await getRepository(Test).insert(test).generatedMaps[0];
Share:
12,748
Michał B
Author by

Michał B

Updated on June 21, 2022

Comments

  • Michał B
    Michał B almost 2 years

    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.