Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering by multiple columns in Prisma

I know currently Prisma doesn't support ordering by multiple scalars fields, (see this issue: https://github.com/prisma/prisma/issues/62). But, I'm wondering if there is someone who found a solution to work around this issue without using executeRaw mutation (raw SQL) because I have many places in my code where I need to order by multiple fields and I don't want to use executeRaw in so many places. I will appreciate any suggestions. Thank you!

like image 887
Andrei Bacescu Avatar asked Sep 14 '25 08:09

Andrei Bacescu


2 Answers

Since Prisma 2.4 this should be basically possible by using array in orderBy:

const users = await prisma.user.findMany({
   select: {
      email: true,
      role: true,
   },
   orderBy: [
      {
         email: 'desc',
      },
      {
         role: 'desc',
      }
   ],
})

Find more in docs: https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#sort-user-by-multiple-fields---email-and-role

like image 130
Fib Avatar answered Sep 17 '25 19:09

Fib


I don't think there's a solution, In my project, I need random order, increment/decrement, aggregation... use raw finally.

like image 39
Gabriel Tong Avatar answered Sep 17 '25 20:09

Gabriel Tong