Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a record and any relationship records in an explicit many to many relationship?

I'm struggling to find documentation for handling explicit many to many relationships in Prisma. So I have resorted to dev by Stackoverflow....

I have a many to many relationship:

model Fight {
  id            Int     @id @default(autoincrement())
  name          String
  fighters      FighterFights[]
}

model Fighter {
  id        Int     @id @default(autoincrement())
  name      String  @unique
  fights    FighterFights[]
}

model FighterFights {
  fighter      Fighter  @relation(fields: [fighterId], references: [id])
  fighterId    Int
  fight        Fight    @relation(fields: [fightId], references: [id])
  fightId      Int

  @@id([fighterId, fightId])
}

I am trying to delete a fight and delete the relationship in FighterFights but not delete the actual fighter.

I tried the following:

const result = await prisma.fight.delete({
  where: {
    id: Number(id),
  },
})

but get the error:

PrismaClientKnownRequestError:
Invalid `prisma.fight.delete()` invocation:
Foreign key constraint failed on the field: `FighterFights_fightId_fkey (index)`

I then also tried:

const result = await prisma.fight.delete({
  where: { id: Number(id) },
  data: {
    fighterFights: {
      deleteMany: {
        where: { fightId: id },
      },
    },
  },
})

But I get the error:

PrismaClientValidationError:
Invalid `prisma.fight.delete()` invocation:

{
  where: {
    id: 1
  },
  data: {
  ~~~~
    fighterFights: {
      deleteMany: {
        where: {
          fightId: '1'
        }
      }
    }
  }
}

Unknown arg `data` in data for type Fight. Available args:

type deleteOneFight {
  where: FightWhereUniqueInput
}

I also tried:

const result = await prisma.fight.delete({
  where: {
    id: Number(id),
  },
  data: {
    fighterFights: {
      deleteMany: [{ fightId: { equals: Number(id) } }],
    },
  },
})

but get the error:

Invalid `prisma.fight.delete()` invocation:

{
  where: {
    id: 1
  },
  data: {
  ~~~~
    fighterFights: {
      deleteMany: [
        {
          fightId: {
            equals: 1
          }
        }
      ]
    }
  }
}

Unknown arg `data` in data for type Fight. Available args:

type deleteOneFight {
  where: FightWhereUniqueInput
}
like image 424
grabury Avatar asked Sep 14 '25 19:09

grabury


1 Answers

Here is the Prisma documentation to disconnect related fields

For single disconnect

const updatePost = await prisma.user.update({
  where: {
    id: 16,
  },
  data: {
    posts: {
      disconnect: [{ id: 12 }, { id: 19 }],
    },
  },
  select: {
    posts: true,
  },
})

To disconnect all

const updateUser = await prisma.user.update({
  where: {
    id: 16
  },
  data: {
    posts: {
      set: []
    }
  },
  include: {
    posts: true
  }
})
like image 197
Shibbir Ahmed Avatar answered Sep 17 '25 19:09

Shibbir Ahmed