question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Support for deep order-by sorting / querying

See original GitHub issue

Problem

Considering the following schema (highly simplified):

model Item {
  id            Int        @id @default(autoincrement()) @db.Int()
  localization  ItemI18n[]
}

model ItemI18n {
  id         Int    @id @default(autoincrement()) @db.Int()
  name       String @db.VarChar(512)
  itemId     Int    @db.Int()
  item       Item   @relation(fields: [itemId], references: [id])

  @@index([itemId], name: "itemId")
}

Using the following SQL Query I can retrieve all items ordered by the name specified in ItemI18n:

SELECT * FROM Item i, ItemI18n i18
ORDER BY i18.name;

But trying the same with prisma fails:

import {PrismaClient} from '@prisma/client';

const prisma = new PrismaClient();

(async () => {
    console.log(
        await prisma.item.findMany({
            orderBy: {
                // Only id is available
            }
        })
    );
})();

Suggested solution

Allowing orderBy to work in both directions (sorry I’m lacking a few terms here)? Something like this:

import {PrismaClient} from '@prisma/client';

const prisma = new PrismaClient();

(async () => {
    console.log(
        await prisma.item.findMany({
            orderBy: {
                localization: {
                    name: 'asc'
                }
            }
        })
    );
})();

Alternatives

None I guess, I could execute a raw query but that’s not doing it in most cases. Or resolve each ItemI18n one-by-one but that’s inherently difficult and cumbersome.

Additional context

I am using:

  • Node: v14.15.5
  • NPM: 7.5.6
  • Prisma: 2.17.0

Issue Analytics

  • State:open
  • Created 3 years ago
  • Reactions:24
  • Comments:26 (7 by maintainers)

github_iconTop GitHub Comments

12reactions
jhackett1commented, Mar 28, 2021

i think this is what i need to. in my case it’s for a chat-like application:

  • find all contacts
  • include the most recent message exchanged (a nested relation)
  • order contacts by the most recent message
  • limit (take?) the number of messages to the last one (since the last message is all that’s shown, and there could be hundreds of messages per contact)

this doesn’t work:

    result = await prisma.contact.findMany({
      orderBy: {
        messages: {
          createdAt: "desc",
        },
      },
      include: {
        messages: {
          orderBy: {
            createdAt: "desc",
          },
          take: 1,
        },
      },
    })

more info on prisma slack

11reactions
jamesopticommented, Apr 15, 2022

Any updates on this? Would love to know if its even been prioritized on the roadmap. Seems like it would be pretty useful for a lot of folks!

Read more comments on GitHub >

github_iconTop Results From Across the Web

SQL Server ORDER BY performance tips
This article will help you uncover the performance secrets of the SQL Server ORDER BY statement.
Read more >
How to create a query with order by deeply nested jsonb data?
I have a table availability with 4 columns: productcode , currency , bookableitems , summary . bookableitems is JSONB. I need to select...
Read more >
Sorting Query Results with Spring Data | Baeldung
In this tutorial, we'll learn how to sort query results with Spring Data. First, we'll take a look at the schema of the...
Read more >
Ordering database queries by relationship columns in Laravel
Ordering by has-many relationships ; 4, having, Filter the aggregated data ; 5, select, Choose the data to return ; 6, order by,...
Read more >
How To Use GROUP BY and ORDER BY in SQL - DigitalOcean
In this tutorial, you will sort query results in SQL using the GROUP BY and ORDER BY statements. You'll also practice implementing aggregate ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found