Prisma 2.0 already has a Dataloader built in exactly for this purpose. This means your resolvers might do multiple calls to findOne but those will be batched into one big SQL query under the hood. So there should be no need for you to implement this optimization on your own.

Answer from mavilein on Stack Overflow
Discussions

How to reproduce a Prisma `include` statement for arrays of related entities without SQL?
In Prisma, I could just do a findMany for channels w/ include the channel_performances. In my case the objective is to retrieve the channels with inside, the channel_performances as array for each channels. Do you know how to do that in Drizzle ORM ? Thank you ! ... You can use few approaches for that 1. Just use simple select with join ... More on answeroverflow.com
🌐 answeroverflow.com
April 20, 2023
How do I do a left join in Prisma?
I believe the Prisma ORM doesn’t do any joins at all. All of the relationship fetching is virtual, and done through multiple sequential queries. I found this issue about it, maybe it can help you. https://github.com/prisma/prisma/discussions/12715 Edit: if you’re asking how to replicate the functionality of a left join without actually doing it, then I’m not sure. I assume using their raw sql function. Sorry, not much help on that one. More on reddit.com
🌐 r/node
16
0
July 27, 2023
How to insert and update element in array
Hi, I am using Prisma2 with GraphQL. Database: Postgres CREATE TABLE "Content" ( "content_id" serial NOT NULL, "content_parent_id" int, "content_name" varcha... More on github.com
🌐 github.com
5
5
mysql - LEFT JOINS and aggregation in a single Prisma query - Stack Overflow
I have a database with multiple tables that frequently need to be queried with LEFT JOIN so that results contain aggregated data from other tables. Snippet from my Prisma schema: model posts { id... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Answer Overflow
answeroverflow.com › m › 1098587416304033972
How to reproduce a Prisma `include` statement for arrays of related entities without SQL? - Drizzle Team
April 20, 2023 - In my case the objective is to ... Thank you ! ... You can use few approaches for that 1. Just use simple select with join and then aggregate results in your code....
🌐
Nico's Blog
nico.fyi › blog › prisma-join-relation
The new join relation in Prisma | Nico's Blog
March 5, 2024 - The final aggregation into JSON arrays is performed using jsonb_agg(), with an ORDER BY clause on the row number to ensure the posts are sorted within each user's array. The LEFT JOIN ensures all users are returned, even those without posts, with post information included only for those who have them. It's intriguing how a task that can be succinctly described in human language ("Getting 10 users and their respective 3 posts") translates into a relatively complex SQL operation. Yet, Prisma simplifies it remarkably.
Find elsewhere
🌐
Prisma
prisma.io › home › select fields › select fields › select fields › select fields
Select fields | Prisma Documentation
Learn how to use select and include in Prisma Client to return only the fields and relations you need.
🌐
DEV Community
dev.to › miyachin › prisma-further-join-on-joined-records-1k00
Prisma: Further JOIN on JOINed records - DEV Community
June 6, 2022 - I had a problem when I wanted to do a further JOIN on JOINed records, so I looked up how to do it. Consider these table structure. (For simplicity, createdAt and updatedAt are omitted.) ... Each group has multiple members, and each member has multiple posts. On schema.prisma, it is defined like this.
🌐
Prisma
prisma.io › blog › prisma-orm-now-lets-you-choose-the-best-join-strategy-preview
Choosing the Best Join Strategy in Prisma ORM: join vs query
February 21, 2024 - To work around these issues, Prisma ORM implements modern, lateral JOINs accompanied with JSON aggregation on the database-level. That way, all the heavy lifting that's needed to resolve the query and bring the data into the expected JavaScript object structures is done on the database-level:
Top answer
1 of 2
18

Despite the accepted answer, the actual answer is: No.

For actual performant joins to work, they must solve an issue that's been open for about a year and a half as of writing this response: https://github.com/prisma/prisma/issues/5184

Currently, there is no way to join tables together. Queries that include relations only include the relational data by using separate queries.

2 of 2
16

Yes, this is possible with Prisma!. For making this work, you need to specify on your "schema.prisma" file how are models related with each other. That way, code generation will set the possible queries/operations.

Change it to this:

model Post {
  id              Int      @id @unique @default(autoincrement()) @map("id")
  userId          Int      @map("user_id")
  movieId         Int      @unique @map("movie_id")
  title           String   @map("title") @db.Text
  description     String?  @map("description") @db.Text
  tags            Json?    @map("tags")
  createdAt       DateTime @default(now()) @map("created_at") @db.DateTime(0)
  image           String?  @default("https://picsum.photos/400/600/?blur=10") @map("image") @db.VarChar(256)
  year            Int      @map("year")
  submittedBy     String   @map("submitted_by") @db.Text
  tmdbRating      Decimal? @default(0.0) @map("tmdb_rating") @db.Decimal(3, 1)
  tmdbRatingCount Int?     @default(0) @map("tmdb_rating_count")
  ratings         Rating[]

  @@map("posts")
}

model Rating {
  id        Int       @unique @default(autoincrement()) @map("id") @db.UnsignedInt
  userId    Int       @map("user_id") @db.UnsignedInt
  rating    Int       @default(0) @map("rating") @db.UnsignedTinyInt
  entryId   Int
  entry     Post      @relation(fields: [entryId], references: [id])
  createdAt DateTime  @default(now()) @map("created_a") @db.DateTime(0)
  updatedAt DateTime? @map("updated_a") @db.DateTime(0)

  @@id([entryId, userId])
  @@map("ratings")
}

Note: Please follow the naming conventions (singular form, PascalCase). I made those changes for you at the schema above. @@map allows you to set the name you use on your db tables.

Then, after generating the client, you will get access to the relational operations.

    // All posts with ratings data
    const postsWithRatings = await prisma.post.findMany({
        include: {
            // Here you can keep including data from other models
            ratings: true
        },
        // you can also "select" specific properties
    });

    // Calculate on your API
    const ratedPosts = postsWithRatings.map( post => {
        const ratingsCount = post.ratings.length;
        const ratingsTotal = post.ratings.reduce((acc, b) => acc + b.rating, 0)
        return {
            ...post,
            userRating: ratingsTotal / ratingsCount
        }
    })

    // OR...


    // Get avg from db
    const averages = await prisma.rating.groupBy({
        by: ["entryId"],
        _avg: {
            rating: true
        },
        orderBy: {
            entryId: "desc"
        }
    })
    //  Get just posts
    const posts = await prisma.post.findMany({
        orderBy: {
            id: "desc"
        }
    });
    // then match the ratings with posts
    const mappedRatings = posts.map( (post, idx) => {
        return {
            ...post,
            userRating: averages[idx]._avg.rating
        }
    })

You could also create a class with a method for making this easier. But I strongly recommend you to implement GraphQL on your API. That way, you can add a virtual field inside your post type. Any time a post is requested alone or in a list, the average will be calculated. In that same way, you would have the flexibility to request data from other models and the "JOINS" will get handled for you automatically.

Last but not least, if you ever want to do a lot of queries at the same time, you can take advantage of the Prisma transactions.

🌐
RedwoodJS Community
community.redwoodjs.com › get help and help others
Best practices for list of Strings in Prisma - Get Help and Help Others - RedwoodJS Community
August 1, 2022 - Hello RW community, What’s the recommended for a list of strings inside a prisma Model? model User { id Int @id @default(autoincrement()) email String @unique hashedPassword String @default("") salt String @default("") resetToken String? resetTokenExpiresAt DateTime? favoriteMovies String[] It seems like we can’t have something like String[] as above.
🌐
Paigeniedringhaus
paigeniedringhaus.com › blog › tips-and-tricks-for-using-the-prisma-orm
Tips and Tricks for Using the Prisma ORM | Paige Niedringhaus
If you’re calling a particular Prisma query for an array of items (like checking which devices have alarm events), be ready to filter out any returned alarm data that is actually undefined so it doesn’t give you false positives. And with that, we’ve covered the majority of the hard won knowledge I gained about Prisma while working with it. Prisma.io is a very powerful, very popular, JavaScript...
🌐
GitHub
github.com › prisma › prisma › issues › 13663
Array as value to Prisma.sql template string · Issue #13663 · prisma/prisma
June 7, 2022 - For example, passing an array of strings in order to perform an IN query. ... const foo = ["buy", "sell"]; prisma.$queryRaw(Prisma.sql`SELECT * FROM "Transaction" WHERE "txType" IN ${foo} LIMIT 1`);
Author   prisma
🌐
Prisma
prisma.io › home › relation queries › relation queries › relation queries › relation queries
Relation queries (Concepts) | Prisma Documentation
join (default): Uses a database-level LATERAL JOIN (PostgreSQL) or correlated subqueries (MySQL) and fetches all data with a single query to the database.
Top answer
1 of 2
5

after many tries i finally got what i want if anyone knows a better way please tell me, i want to learn, for now this is my solution:

i need to send each value as id: playlistId

const song = await prisma.song.findUnique({
    select: {
       playlists: true
     },
     where: {
        id: +songId
     }
})

//   get an array of objects, id: playlistId
const songPlaylistsIds = song.playlists.map( playlist => ({id: playlist.id}))

//   I prepare the array with the content that already exists plus the new content that I want to add:
const playlists =  [...songPlaylistsIds, { id: playlistId}]

await prisma.song.update({
       where: { id: +songId },
       data:{
          playlists: {
             // finally for each object in the array i get, id: playlistId and it works.
             set: playlists.map( playlistSong => ({ ...playlistSong })) 
          }                
       }
})

Problems I had doing this: I was wrong in thinking that it should work as simple as playlist: lists I wanted to change the content to a new one but I couldn't, I needed to send the values ​​one by one. Another error when I get the content of the playlists. I had the full object but just needed to send the id. And lastly, in the prisma documentation, there is a method like set, push, but this method doesn't work, at least I don't know how to make push work

2 of 2
1

I find a solution :
https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#add-new-related-records-to-an-existing-record

await prisma.song.update({
       where: { id: +songId },
       data:{
          playlists:{
              create:{
                 data:{ id: playlistId}
              }
          }                
       }
})