2

次の Prisma スキーマを検討してください。

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])
}

このようなクエリを実行して、メッセージの日付順に並べられた会話のリスト、つまり新しいメッセージが最初にある会話のリストを取得したいと考えています。

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

しかし、私が今クエリできる唯一の方法は、このようなものです。つまり、リレーションは_countどういうわけかプロパティしか持っていません。

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

環境とセットアップ


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

プリズマ版

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

ありがとう!

4

3 に答える 3

0

このプレビュー機能が有効になっている場合、1 対多の関係で並べ替えることができるようになりました。

One-to-Many
For one-to-many relationships, you can order by the relation from one side:

✅ Order posts by their author's name

⛔️ Order authors by their post's titles

model Author {
  id Int @id
  name String
  posts Post[]
}

model Post {
  id Int @id
  title String
  author Author
}
prisma.post.findMany({
  orderBy: [{
    author: {
      name: 'asc'
    }
  }]
})

https://github.com/prisma/prisma/issues/5008を参照してください。

于 2021-10-29T15:26:44.593 に答える