typescript - Is it possible to modify the SQL query in the beforeQuery event of a Subscriber in TypeORM? - Stack Overflow

I’m trying to intercept and modify an SQL query in the beforeQuery event of a Subscriber in TypeORM to

I’m trying to intercept and modify an SQL query in the beforeQuery event of a Subscriber in TypeORM to add custom subqueries based on the selected fields.

For example, I want to replace a totalPrice field with a custom SQL subquery:

@EventSubscriber()
export class BookingSubscriber implements EntitySubscriberInterface<Booking> {
  listenTo() {
    return Booking;
  }

  beforeQuery(event: BeforeQueryEvent<Booking>) {
    let newQuery = event.query;

    if (newQuery.includes('totalPrice')) {
      // Example replacement
      newQuery = newQuery.replace(
        'totalPrice',
        '(SELECT SUM(price) FROM booking_item WHERE booking_item.bookingId = booking.id) AS totalPrice',
      );
    }

    event.query = newQuery;
  }
}

However, I’ve noticed that the event object passed as a parameter seems to be a copy of the original one since the changes I make to event.query are not reflected in the final query executed by TypeORM. This results in an error indicating that the totalPrice field doesn’t exist in the database (because it wasn’t replaced in the final SQL).

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742312249a4420127.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信