JV Lobo
JV Lobo

Reputation: 6316

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

Upvotes: 4

Views: 1968

Answers (2)

Noby Fujioka
Noby Fujioka

Reputation: 1824

I came across the same issue with Prisma and this is a major problem. Retrieving all the users with all their posts, and sorting by the number of their posts is not a practical solution.

The workaround I can think of is to track the number of posts (every time when adding/deleting)and store it in User.

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

This way, Prisma will expose the sorting options for the postsCount.

I am not sure if Prisma 2 offers a proper solution for this issue... Does anybody know?

Upvotes: 0

Errorname
Errorname

Reputation: 2459

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

Upvotes: 3

Related Questions