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.
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();
Try this
let test: Test = [{ firstName: "test", lastName: "test" }];
test = await getRepository(Test).insert(test).generatedMaps[0];
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With