'How to create a trigger in nestjs with typeorm?
Is there any way to create a trigger in nestjs/typeorm. This trigger should
- Auto-increment a column whenever that row is updated
- Work even when working directly in mysql database
Solution 1:[1]
Don't know whether @nestjs/typeorm has that functionality or not but the core typeorm package do support triggers out of the box.
You can try something like this using the core typeorm package :
@EventSubscriber()
export class PostSubscriber implements EntitySubscriberInterface {
/**
* Called before entity update.
*/
beforeUpdate(event: UpdateEvent<any>) {
console.log(`BEFORE ENTITY UPDATED: `, event.entity)
manager.update(YourEntity, { yourColumn : value })
}
/**
* Called after entity update.
*/
afterUpdate(event: UpdateEvent<any>) {
console.log(`AFTER ENTITY UPDATED: `, event.entity)
}
}
The event object contains :
- dataSource: DataSource - DataSource used in the event.
- queryRunner: QueryRunner - QueryRunner used in the event transaction.
- manager: EntityManager - EntityManager used in the event transaction.
Note: All database operations in the subscribed event listeners should be performed using the event object's queryRunner or manager instance.
You can further read about this at https://typeorm.io/listeners-and-subscribers#what-is-a-subscriber.
Do let me know if this solves your issue.
Solution 2:[2]
I fixed this issue by explicitly creating triggers in mysql.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Afaq Javed |
| Solution 2 | Open Wings Infotech |
