I am trying to get most recent transaction by using this query inside my NestJs application
public findUsersWithRecentTransactions(): Promise<UserEntity[]> {
return this.createQueryBuilder('users')
.innerJoinAndSelect('users.transactions', 'transactions')
.where(
'(users.userType = :userTypeParent AND users.registrationStatus = :registrationStatusParent)',
{
userTypeParent: UserType.Parent,
registrationStatusParent: RegistrationStatus.onboarded,
},
)
.orderBy('transactions.created_at', 'DESC').getMany();
}
This returns an array of transactions sorted by their created_at date in descending order. However, I am trying to get the most recent transaction using the query itself so that I don't have to loop over the entities to get the transaction.
const usersWithTransactions = await this.userRepository.findAllUsersWithTransactions();
for (const user of usersWithTransactions) {
const mostRecentTransaction = user?.transactions[0];
Hi you should try limit method.
public findUsersWithRecentTransactions(): Promise<UserEntity[]> {
return this.createQueryBuilder('users')
.innerJoinAndSelect('users.transactions', 'transactions')
.where(
'(users.userType = :userTypeParent AND users.registrationStatus = :registrationStatusParent)',
{
userTypeParent: UserType.Parent,
registrationStatusParent: RegistrationStatus.onboarded,
},
)
.orderBy('transactions.created_at', 'DESC')
.limit(1) // I include this.
.getMany();
}
Check this code above. I added '.limit(1)'.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.