Skip to content

Specify per-relation load strategy #22759

@itsgiacoliketaco

Description

@itsgiacoliketaco

Note: this feature is related to the relationJoins preview feature launched in Prisma 5.8.0, and was discussed here.

Problem

It is often beneficial to use joins to load relations in a query, but it is sometimes better to load the related objects with a separate query. This depends on the specific relationship in question. It would be useful to mix-and-match relation load strategies in a single Prisma query call.

For example, when loading many posts for a given author, we know that post.author will be the same for every post. If there are many posts, it may be faster to load the author once in separate query instead of receiving N copies of the same author from the database. However, if posts are categorized, then post.category can differ between posts, so joins may be favorable for this relation.

Suggested solution

I suggest the following API as a more granular version of the relationLoadStrategy option:

db.posts.findMany({
  // This existing option specifies the default load strategy for all included relations.
  // If unspecified, it inherits the global default.
  relationLoadStrategy: 'join',

  where: {
    // Only load posts for a specific author.
    authorId: '123',
  },

  include: {
    // Load `post.category` via JOIN.
    category: { loadStrategy: 'join' },

    // Load `post.author` with a separate query.
    author: {
      loadStrategy: 'query',

      include: {
        // Inherits the default as specified in `relationLoadStrategy` at the top of this `findMany` call.
        // In this case `true` is equivalent to `{ loadStrategy: 'join' }`.  It does NOT inherit the `loadStrategy`
        // specified for the `author` relationship.
        avatarImage: true,
      }
    },

    // `true` is equivalent to `{ loadStrategy: 'join' }` here.
    bannerImage: true,
  },
})

Alternatives

You can remove author from the include, make a separate Prisma call to load the author, and then perform the "join" manually by iterating and attaching the author object to all the post objects.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions