Michał B
Michał B

Reputation: 473

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.

Upvotes: 12

Views: 42142

Answers (5)

juztcode
juztcode

Reputation: 1355

If raw queries are being used then something like this could be done: queryRunner.query('insert into .... returning *);

Upvotes: 0

Istiaq Ahmed
Istiaq Ahmed

Reputation: 166

In case of mssql I was struggling to get the accepted answer working. Later figured out - in the returning("your_id_column_name") part, we need to rather provide returning("inserted.your_id_column_name") to get the inserted id column value. Note that in my case the id column was an identity column and decorated with PrimaryColumn and insert:false option from typeorm side.

Upvotes: 0

juantapia1999
juantapia1999

Reputation: 31

try this

const testRepo = getRepository(Test)    
let insert = await testRepo()
           .createQueryBuilder()
           .insert()
           .into(Test)
           .values([
               { firstName: "test", lastName: "test" }
            ])
           .execute();
console.log("id: ",insert.raw.insertId);

after you will get an object with some properties, one of the properties is "raw" and inside "insertId".
in this case: insert.raw.inserId --> is the id of the insert.
P.D.: sorry for my English

Upvotes: 3

Alfonso Alonso
Alfonso Alonso

Reputation: 31

Try this

let test: Test = [{ firstName: "test", lastName: "test" }];
test = await getRepository(Test).insert(test).generatedMaps[0];

Upvotes: 3

noam steiner
noam steiner

Reputation: 4444

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

Upvotes: 14

Related Questions