Hey guys, I’ve got a situation where I want/need ...
# random
r
Hey guys, I’ve got a situation where I want/need to order on fields which are located in a one-to-many relation. Now I’ve read most of the resources concerning Prisma’s current state on this topic, references: https://github.com/prisma/prisma/issues/5008#issuecomment-768444693 https://www.prisma.io/docs/concepts/components/prisma-client/filtering-and-sorting#sort-by-relation One-to-Many For one-to-many relationships, you can order by the relation from one side: Order posts by their author’s nam Order authors by their post’s title
Copy code
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'
    }
  }]
})
So my problem (looking at the above example from the github issue) is that I actually DO want to order the authors on the post’s titles. And I was wondering in what ways I could achieve besides just using raw queries, which I obv. want to avoid.. Any help or advice is welcome! prisma green💌
j
I haven't slept yet (am in the US lol), so I may not be understanding this clearly.. but I'm pretty sure you can put an
orderBy
at both levels of the query
r
As far as I’ve seen I can only
orderBy
on-to-one relations. The one-to-many is limited on an aggregation ordering which only supports a
count
I’d like to achieve this:
Copy code
prisma.author.findMany({
  orderBy: [{
    posts: {
      title: 'asc'
    }
  }]
})
j
and that doesn't work? i can make a scratch project and try to help if you want
r
No, because the hasMany relations only receive a
PostsOrderByRelationAggregateInput
Copy code
{
    _count?: SortOrder
  }
And you should be in bed, sir. 😄
j
eh, it's only 6am. we'll at least try to figure this out 💯
ok, confirming what you said is indeed accurate. stupid aggregate input type
r
Yup.. So I’m look at alternatives. Was just looking at using views, but this doesn’t seem mature enough with Prisma and looks like a real hassle to use now.
j
i was looking at groupBy as a potential (hacky) way to do it
still probably wouldn't fit the bill tbh
c
I think you want to use
include
i.e.
Copy code
prisma.post.findMany({
  include: {
    author: true,
    orderBy: {
      name: 'asc'
    }
  },
  orderBy: {
    title: 'asc'
  }
})
...or something like that, I just wrote it from memory but I'm sure you get the idea...let Prisma help you out by pressing control-spacebar in VS Code for hints.