Search code examples
postgresqltypeorm

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?


Solution

  • 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.