Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query to get data ordered by the number of items in a relation

Let’s say I have this typical datamodel, the one used in many tutorials:

type User {
  id: ID! @unique
  name: String!
  posts: [Post!]!
}

type Post {
  id: ID! @unique
  title: String!
  content: String!
  published: Boolean! @default(value: "false")
  author: User!
}

Is there a query I can build to get a list of, let’s say, the 10 Users with more Posts?? Basically I need to query ordering by “count” of Posts… but I haven’t found a way to do it

Any help will be highly appreciated

Cheers

like image 741
JV Lobo Avatar asked Oct 15 '25 19:10

JV Lobo


1 Answers

As @shivam-panday said in a comment, this is currently not implemented in Prisma (See issue: https://github.com/prisma/prisma/issues/95 )

This comment especially explains your problem:

It would be great to be able to order by "to-many" related fields as well (by the count of related items).

For example, to get a list of the top 10 most voted-for links (assuming votes is a related field of type [Vote!]!):

query {
  allLinks(first: 10, orderBy: votes_DESC) {
    id
    url
    description
    _votesMeta {
      count
    }
  }
}

Currently, to get that list you'd have to query for every Link and then sort/slice it on the client, which is potentially a ton of overfetching.

Comment in question: https://github.com/prisma/prisma/issues/95#issuecomment-320433296

like image 145
Errorname Avatar answered Oct 18 '25 15:10

Errorname