Has anyone had issues with ordering when using `fi...
# orm-help
f
Has anyone had issues with ordering when using
findOne
with relations fields? Our model specifically does not have a field which we can use to enforce order (via
orderBy
), we just want the data read in the same order we wrote it the DB. Do we need to add an explicit order field to guarantee this order (this is what we are currently thinking of doing)? Thought we'd ask here in case anyone might have encountered this before, any help would be much appreciated, thanks! 😊
r
@fondfolio 👋 Suppose I have a model of User and Post:
Copy code
model Post {
  id        Int      @default(autoincrement()) @id
  published Boolean  @default(false)
  title     String
  content   String?
  authorId  Int?
  author    User?    @relation(fields: [authorId], references: [id])
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

model User {
  id        Int      @default(autoincrement()) @id
  name      String?
  posts     Post[]
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}
I can order relation fields like this:
Copy code
await prisma.user.findOne({
    where: { id: 1 },
    select: { posts: { orderBy: { id: 'asc' } } },
  })
Is this the behaviour you were looking for?
f
@Ryan yes
👍 1
c
@Ryan in the example above (
User
has
Posts
) if we were writing the User and Posts as one
prisma.user.create
(with a nested
create
for Posts), is there a way to guarantee they are read in the same order we wrote them in? I see you are relying on the
autoincrement()
id, but just wondering if there is a way around that. Thanks! 🙏
r
Maybe order by
createdAt
?
Copy code
await prisma.user.findOne({
    where: { id: u.id },
    select: {
      name: true,
      posts: { select: { title: true }, orderBy: { createdAt: 'asc' } },
    },
  })
c
Unfortunately, because we are inserting them as a nested create, the createdAt/updatedAt values are all the same.
My best solution right now to add a
order
field
Which is not ideal, but would probably work
r
Multiple order by’s, one from
createdAt
and the other from
id
. That will always be deterministic.