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.

_count doesn't update in many to many relation

See original GitHub issue

Bug description

I have many-to-many relations in my schema like brand and category. I am using _.count to see how many brands are there in a category. It seems to work but when I delete one of the brand it does not update _.count in the category.

This is the model :

model Category {
  id        String              @id @default(cuid())
  name       String              @unique
  createdAt DateTime            @default(now())
  brands Brand[]
}

model Brand {
  id         String              @id @default(cuid())
  name       String              @unique
  createdAt  DateTime            @default(now())
  categories   Category[] 
}

I am showing how many brands in a category by pulling the data like this

   const Data = await prisma.category.findMany({
        include: {
          _count: {
            select: { brands: true }
          }
        }
      });

It works fine. It shows how many brands are in a category. When I try to delete a brand like this;

 prisma.brand
      .delete({
        where: {
          id: ID
        }
      })

The brand gets deleted but the category list doesn’t update. It still includes that brand in _count. I have deleted the same way in one-to-many relation where _count updated. How do I do it in many to many?

How to reproduce

The project is complicated so If you want you can use just two models to follow the bugs

model Category {
  id        String              @id @default(cuid())
  name       String              @unique
  createdAt DateTime            @default(now())
  brands Brand[]
}

model Brand {
  id         String              @id @default(cuid())
  name       String              @unique
  createdAt  DateTime            @default(now())
  categories   Category[] 
}

Expected behavior

When I delete a brand, the Category list (._count) also should be updated. like when I use this code to see.

   const Data = await prisma.category.findMany({
        include: {
          _count: {
            select: { brands: true }
          }
        }
      });

Environment & setup

  • OS: Windows 10
  • Database: MySQL
  • Node.js version: v16.14.1

Prisma Version

prisma                  : 3.11.0
@prisma/client          : 3.11.0
Current platform        : windows
Query Engine (Node-API) : libquery-engine b371888aaf8f51357c7457d836b86d12da91658b (at node_modules\@prisma\engines\query_engine-windows.dll.node)
Migration Engine        : migration-engine-cli b371888aaf8f51357c7457d836b86d12da91658b (at node_modules\@prisma\engines\migration-engine-windows.exe)
Introspection Engine    : introspection-core b371888aaf8f51357c7457d836b86d12da91658b (at node_modules\@prisma\engines\introspection-engine-windows.exe)
Format Binary           : prisma-fmt b371888aaf8f51357c7457d836b86d12da91658b (at node_modules\@prisma\engines\prisma-fmt-windows.exe)
Default Engines Hash    : b371888aaf8f51357c7457d836b86d12da91658b
Studio                  : 0.458.0
Preview Features        : referentialIntegrity

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:1
  • Comments:8 (6 by maintainers)

github_iconTop GitHub Comments

2reactions
Sakkhor909commented, Sep 8, 2022

Yes. The issue has solved!!!

1reaction
jkomynocommented, Aug 9, 2022

I can confirm this bug with the current version of Prisma with referentialIntegrity = prisma. If we use referentialIntegrity = foreignKeys, instead, everything seems to be fine. I have target databases MySQL 8.0 and Postgres 14, but the issue doesn’t seem connector-related.

Schema

    generator client {
      provider = "prisma-client-js"
      previewFeatures = ["referentialIntegrity"]
    }
    
    datasource db {
      provider = "mysql"
      url      = env("DATABASE_URI_MYSQL")
      referentialIntegrity = "prisma"
    }
    
    model Category {
      id     String  @id @default(cuid())
      name   String  @unique
      brands Brand[]
    }
    
    model Brand {
      id         String     @id @default(cuid())
      name       String     @unique
      categories Category[] 
    }

## Test

await prisma.category.create({
  data: {
    name: 'cat-1',
    brands: {
      create: [{ name: 'brand-1' }, { name: 'brand-2' }],
    },
  },
})

await prisma.category.create({
  data: {
    name: 'cat-2',
    brands: {
      create: [{ name: 'brand-3' }, { name: 'brand-4' }],
    },
  },
  include: { brands: true },
})

const categories = await prisma.category.findMany({
  include: {
    _count: {
      select: { brands: true },
    },
  },
})
expect(categories).toMatchObject([
  {
    _count: { brands: 2 },
    name: 'cat-1',
  },
  {
    _count: { brands: 2 },
    name: 'cat-2',
  }
])

await prisma.brand.delete({ where: { name: 'brand-1' } })

const categoriesAfterBrand1Deletion = await prisma.category.findMany({
  include: {
    _count: {
      select: { brands: true },
    },
  },
})
expect(categoriesAfterBrand1Deletion).toMatchObject([
  {
    _count: { brands: 1 }, // the count is 2 with referentialIntegrity = prisma
    name: 'cat-1',
  },
  {
    _count: { brands: 2 },
    name: 'cat-2',
  }
])
Read more comments on GitHub >

github_iconTop Results From Across the Web

JPA update doesn't work in a many-to-many relationship
There is a @ManyToMany relation between customer and sales_person . When I perform a delete, then it works fine: the customer , is_managed ......
Read more >
Update the data that has many to many relationship - Laracasts
Hi,. I have 2 models which are Developers and Projects. A developer can have many projects and a project can have many developers....
Read more >
Guide to table relationships - Microsoft Support
A one-to-many relationship. Let's use an order tracking database that includes a Customers table and an Orders table as an example. · A...
Read more >
4.10. Updating a DataSet with a Many-to-Many Relationship
This method creates random data in both the parent and child tables and randomly creates relationships between them by adding records to the...
Read more >
Many-to-many relationships - Django documentation
To define a many-to-many relationship, use ManyToManyField . In this example, an Article can be published in multiple Publication objects, and a Publication ......
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