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.

findMany broken with many relations to same entity

See original GitHub issue

Bug description

When making a findMany query to an entity (A) that has a ManyToMany relation to another entity (B), if B is referred to in many of the returned A entities, only one of the A entities actually has B returned.

How to reproduce

  1. Run a findMany query with a Many to Many relationship
  2. Have many of the base entities reference the same related entity
  3. Only one of the base entities will have the related entity in the response

Expected behavior

All related entities should be returned correctly in the prisma mapping.

Prisma information

Schema

datasource db {
  url      = env("DATABASE_URL")
  provider = "postgresql"
}

generator client {
  provider = "prisma-client-js"
  output   = "../node_modules/@prisma/client/generated"
}

model Group {
  groupId   BigInt   @id
  users     User[]
  tags      Tag[]
  broadcasts Boolean @default(true)
  adminOnly Boolean @default(false)
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
}

model User {
  userId     BigInt     @id
  groups     Group[]
  tags       Tag[]
  username   String?
  firstName  String?
  lastName   String?
  lastSeen   DateTime   @default(now())
  createdAt  DateTime   @default(now())
  updatedAt  DateTime   @updatedAt
}

model Tag {
  tagId      String     @id @default(uuid())
  name       String
  group      Group      @relation(fields: [groupId], references: [groupId])
  groupId    BigInt
  users      User[]
  lastUsed   DateTime?
  createdAt  DateTime   @default(now())
  updatedAt  DateTime   @updatedAt

  @@unique([name, groupId])
}

Query

const tags = await prisma.tag.findMany({
  where: { groupId },
  include: { users: true }
});

Environment & setup

  • OS: Windows and Linux
  • Database: PostgreSQL
  • Node.js version: v14.17.5

Prisma Version

$ prisma -v                                                       
Environment variables loaded from .env
prisma                  : 3.10.0
@prisma/client          : 3.10.0
Current platform        : windows
Query Engine (Node-API) : libquery-engine 73e60b76d394f8d37d8ebd1f8918c79029f0db86 (at node_modules\@prisma\e
ngines\query_engine-windows.dll.node)
Migration Engine        : migration-engine-cli 73e60b76d394f8d37d8ebd1f8918c79029f0db86 (at node_modules\@pri
sma\engines\migration-engine-windows.exe)
Introspection Engine    : introspection-core 73e60b76d394f8d37d8ebd1f8918c79029f0db86 (at node_modules\@prism
a\engines\introspection-engine-windows.exe)
Format Binary           : prisma-fmt 73e60b76d394f8d37d8ebd1f8918c79029f0db86 (at node_modules\@prisma\engine
s\prisma-fmt-windows.exe)
Default Engines Hash    : 73e60b76d394f8d37d8ebd1f8918c79029f0db86
Studio                  : 0.458.0

Example:

This query:

const tag = await prisma.tag.findUnique({
  select: { users: true, name: true },
  where: { name_groupId: { groupId, name } },
  rejectOnNotFound: false
});

returns the following for the respective args:

(groupid: A, name: 'test')
{
  users: [
    {
      userId: 87425504n,
      username: 'zackpollard',
      firstName: 'Zack',
      lastName: 'Pollard',
      lastSeen: 2022-03-09T00:43:48.688Z,
      createdAt: 2022-02-28T02:42:03.063Z,
      updatedAt: 2022-03-09T00:43:48.721Z
    }
  ],
  name: 'test'
}

(groupId: A, name: 'test2')
{
  users: [
    {
      userId: 87425504n,
      username: 'zackpollard',
      firstName: 'Zack',
      lastName: 'Pollard',
      lastSeen: 2022-03-09T00:44:49.338Z,
      createdAt: 2022-02-28T02:42:03.063Z,
      updatedAt: 2022-03-09T00:44:49.340Z
    }
  ],
  name: 'test2'
}

The findMany query for the same group:

const tags = await prisma.tag.findMany({
  where: { groupId },
  include: { users: true }
});

Returns:

(groupId: A)
[
  {
    tagId: 'b573fab0-1043-480c-a1c1-51edd1eff4c3',
    name: 'test',
    groupId: -747796799n,
    createdAt: 2022-02-28T02:42:03.296Z,
    updatedAt: 2022-02-28T02:42:03.296Z,
    users: []
  },
  {
    tagId: 'f2357c37-a468-461a-bc15-d05f010eb787',
    name: 'test2',
    groupId: -747796799n,
    lastUsed: null,
    createdAt: 2022-03-09T00:20:00.584Z,
    updatedAt: 2022-03-09T00:20:00.585Z,
    users: [ [Object] ]
  }
]

As you can see, the first tag “test” is missing the user that “test2” shares with it

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:11 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
zackpollardcommented, Jun 23, 2022

Hey folks,

Either I’m doing something wrong or there’s something going on with your data. Either way, I unfortunately can’t reproduce your issue.

image

Would you mind setting up a small reproduction with seed data?

Thank you 🙏

Hey Weakky,

It’s been a while since i’ve worked on this code. However the issue exists when two entities (tags) return a nested array of entities (users) that share one of the related entities, i.e. both have the same user connected to the tag. In that case, only one of the tags shows the user whereas both should show it. In your data set if you add Flavian to tag_b or Zack to tag_a you should see the problem.

Cheers!

0reactions
zackpollardcommented, Jun 27, 2022

Excellent, thankyou for resolving it @Weakky

Read more comments on GitHub >

github_iconTop Results From Across the Web

Prisma Client API (Reference)
findFirst calls findMany behind the scenes and accepts the same query options. ... query breaks the connection between a parent record and a...
Read more >
Entity Framework Core: many-to-many relationship with same ...
I am trying to map many-to-many relationship with the same entity. The User entity has an IList<User> data field for Contacts , which...
Read more >
prisma findmany where not null - You.com | The Search Engine You ...
Run a findMany query with a Many to Many relationship; Have many of the base entities reference the same related entity; Only one...
Read more >
6892 Cannot find many entity which is referencing the one entity.
6892 Cannot find many entity which is referencing the one entity. ... Guidelines for Defining Related Entities in the Component Structure.
Read more >
One-to-Many & Many-to-Many Relationships
The ORDER and ITEM entities in our example have a many-to-many relationship. The primary key of each data entity is stored as a...
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