Quick question… can `findMany` preserve id orderi...
# orm-help
l
Quick question… can
findMany
preserve id ordering? E.g. …
Copy code
const getUser = await prisma.user.findMany({
  where: {
    id: { in: [22, 91, 14, 2, 5] },
  },
})
and guarantee the order of the users is always 22, 91, etc? I can only come up with a manual solution, but I’m not sure how performant it is against Prisma’s findMany, e.g.
Copy code
const getUsers = (await Promise.all(ids.map(id => prisma.user.findUnique({ where: { id }})))
1
a
Hey there! I think queries are ordered by ascending
id
by default, so the order would not be preserved in this case. Could you sort the array of ids before passing it to the query? That way it would be synced with the query results. Or do you have another use case?
j
Just re-order the result of the findMany, don't convert it to a bunch of individual findUniques.
Copy code
const ids = [22, 91, 14, 2, 5];
const users = prisma.user.findMany({
  where: {
    id: { in: ids },
  },
});
const sorted = ids.map(id => users.find(user => user.id === id));
^ here
sorted
contains the users in the same order as
ids
l
Thanks Jacob.. I ended up with a sort function as you suggested and it worked fine.
👍 1