Search code examples
sqlpostgresqlprismaprisma2

prisma Order by relation has only _count property. Can not order by relation fields


consider following Prisma schema:

model Conversation {
  id           Int                         @id @default(autoincrement())
  createdAt    DateTime                    @db.Timestamp(6)
  messages     ConversationMessage[]
}

model ConversationMessage {
  id             Int                     @id @default(autoincrement())
  text           String                  @db.VarChar(1000)
  sentAt         DateTime                @map("sent_at") @db.Timestamp(6)
  conversationId Int?                    @map("conversation_id")
  userId         Int?                    @map("user_id")
  conversation   Conversation?           @relation(fields: [conversationId], references: [id])
  sender         User?                   @relation(fields: [userId], references: [id])
}

I want to run such query so that I get a list of conversations ordered by date of their messages, i.e. the ones with new messages first.

prisma.conversation.findMany({
    orderBy: {
        messages: {
            sentAt: 'desc'
        }
    },
    ...
})

But the only way that I can query now is like this, i.e. relation has only _count property somehow.

prisma.conversation.findMany({
    orderBy: {
        messages: {
           '_count': 'desc'
        }
     },
     ...
})

Environment & setup


    OS: Mac OS,
    Database: PostgreSQL
    Node.js version: v12.19.0

Prisma Version

prisma               : 2.24.1
@prisma/client       : 2.24.1
Current platform     : darwin
Query Engine         : query-engine 18095475d5ee64536e2f93995e48ad800737a9e4 (at node_modules/@prisma/engines/query-engine-darwin)
Migration Engine     : migration-engine-cli 18095475d5ee64536e2f93995e48ad800737a9e4 (at node_modules/@prisma/engines/migration-engine-darwin)
Introspection Engine : introspection-core 18095475d5ee64536e2f93995e48ad800737a9e4 (at node_modules/@prisma/engines/introspection-engine-darwin)
Format Binary        : prisma-fmt 18095475d5ee64536e2f93995e48ad800737a9e4 (at node_modules/@prisma/engines/prisma-fmt-darwin)
Default Engines Hash : 18095475d5ee64536e2f93995e48ad800737a9e4
Studio               : 0.397.0
Preview Features     : orderByRelation

Thank You!


Solution

  • For such cases I use rawQuery method and write custom select e.g.

    export async function getConversationsOrderedByMessageSentAt() {
      return db.$queryRaw`SELECT c.*
        FROM conversation c
        JOIN messages m
            ON c.id = m. conversationId
        ORDER BY m.sentAt DESC;`;
    }
    

    This approach does not require sorting on backend side, so performance is not affected.