Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update with returning values in TypeORM?

I wanted to update values and to return specified columns with PostgreSQL.

So far, what I found was update the value then use findOne, but then again it will always use two queries to achieve what I want.

Another is using RAW SQL, UPDATE ... SET ... WHERE ... RETURNING * and this seems a great solution so is there a way to achieve this with TypeORM using UpdateQueryBuilder?

like image 502
JeromeDL30 Avatar asked Oct 21 '25 15:10

JeromeDL30


1 Answers

You can use createQueryBuilder:

const firstUser = await connection
    .getRepository(User)
    .createQueryBuilder("user")
    .update<User>(User, {firstName: 'new first name'})
    .where("user.id = :id", { id: 1 })
    .returning(['id', 'email'])
    .updateEntity(true)
    .execute();

Notice: there are many ways in type orm to use createQueryBuilder such as: BaseEntity, Repository, EntityManager.

like image 139
noam steiner Avatar answered Oct 23 '25 06:10

noam steiner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!