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条)