Skip to content
Advertisement

TypeORM – How to remove last added row?

I’m trying to remove only the last added row. Instead, of the last one, it removes all rows.

this.connection.getRepository(EditorEvent)
    .createQueryBuilder('editor_events')
    .orderBy('created_at', 'DESC')
    .limit(1)
    .delete()
    .execute();

I was thinking about adding where corresponding to the newest date but I feel it’s not a good approach to solve this problem.

Advertisement

Answer

Use a subquery to query the last insert row first, then delete this row by the returned id:

await connection.getRepository(EditorEvent).createQueryBuilder()
    .delete()
    .where(qb => `id IN (${qb.createQueryBuilder()
            .select('id')
            .from(EditorEvent, 'ev')
            .orderBy('created_at', 'DESC')
            .limit(1)
            .getQuery()})`;
    ).execute();
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement