Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get soft deleted entity from typeorm postgreSQL?

I am trying to get soft deleted doc from postgreSQL database using typeorm find, findOne or query builder get/getMany methods, but it always return undefined. Is there a way to get deleted value?

By the docs it should only set a timestamp for deletedAt, and it definitely works, because I can update same record using update where from query builder.

like image 409
Jurgis Avatar asked Oct 13 '20 14:10

Jurgis


3 Answers

I found out there is another solution. You can use the querybuilders .withDeleted() method to also return soft deleted entities.

Example

 const query = await this.manager
        .getRepository(FolderEntity)
        .withDeleted() 
        .createQueryBuilder('folder')
        .leftJoinAndSelect('folder.subStatus', 'status')
        .getMany()
like image 160
BunyamiN Avatar answered Sep 28 '22 19:09

BunyamiN


Actually referring to the findOptions doc you can pass the withDeleted boolean that will retrieve the soft deleted rows.

for example:

const result = await this.repo.find({ where: { id }, withDeleted: true })
like image 27
Sufiane Avatar answered Sep 28 '22 18:09

Sufiane


After more searching I found that only solution is to use raw sql query for that as it is shown in typeorm docs at the query block.

const deletedEntity = await connection
    .getRepository(Entity)
    .query(`SELECT * FROM Entity where id = '${deletedEntityId}'`)

This query returns values with deletedAt timestamp.

like image 28
Jurgis Avatar answered Sep 28 '22 18:09

Jurgis