Reputation: 164
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
Reputation: 18389
There are many options:
em.findOne
to load just the right entity (e.g. em.findOne(Account, { user })
)user.accounts.matching
that has a limit
option: https://mikro-orm.io/docs/collections#filtering-collections@Formula
decorator: https://mikro-orm.io/docs/defining-entities#formulasUpvotes: 1