Abdlrahman Saber
Abdlrahman Saber

Reputation: 164

How get the last element in the table in the relationship in an efficient way?

let's say I have an entity called user and each user has many accounts, and I want to get the last account inserted in a specific user.

I tried different solutions but I didn't find a better one, I had to get a user and then use loadItems method with orderBy desc and then get first element but I don't want to load all accounts from DB.

that's what I did

const user = await this.repository.find({id})
const accounts = await user.accounts.loadItems({orderBy: {['column']: 'DESC'}})

return accounts[0];

that's absolutely not a good solution because I load all items from the database first, is there any other way to do it? I'm still new in MikroOrm so I'll appreciate any suggestions.

Thanks in advance.

Upvotes: 0

Views: 1298

Answers (1)

Martin Adámek
Martin Adámek

Reputation: 18389

There are many options:

Upvotes: 1

Related Questions