Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 338
Michał B Avatar asked May 03 '20 21:05

Michał B


3 Answers

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

like image 67
noam steiner Avatar answered Oct 13 '22 11:10

noam steiner


Try this

let test: Test = [{ firstName: "test", lastName: "test" }];
test = await getRepository(Test).insert(test).generatedMaps[0];
like image 34
Alfonso Alonso Avatar answered Oct 13 '22 10:10

Alfonso Alonso


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

like image 41
juantapia1999 Avatar answered Oct 13 '22 11:10

juantapia1999