简体   繁体   English

使用 Prisma2 和 Jest 删除表中的所有项目

[英]Remove all items in table with Prisma2 and Jest

I would like to know how can I remove all items in table with Prisma2 and Jest?我想知道如何使用 Prisma2 和 Jest 删除表中的所有项目?

I read the CRUD documentation and I try with this:我阅读了CRUD 文档并尝试使用:

user.test.js user.test.js

....
import { PrismaClient } from "@prisma/client"

beforeEach(async () => {
    const prisma = new PrismaClient()
    await prisma.user.deleteMany({})
})
...

But I have an error:但我有一个错误:

Invalid `prisma.user.deleteMany()` invocation:
The change you are trying to make would violate the required relation 'PostToUser' between the `Post` and `User` models.

My Database我的数据库

CREATE TABLE User (
  id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
  name VARCHAR(255),
  email VARCHAR(255) UNIQUE NOT NULL,
  password VARCHAR(255) NOT NULL
);

CREATE TABLE Post (
  id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
  title VARCHAR(255) NOT NULL,
  createdAt TIMESTAMP NOT NULL DEFAULT now(),
  content TEXT,
  published BOOLEAN NOT NULL DEFAULT false,
  fk_user_id INTEGER NOT NULL,
  CONSTRAINT `fk_user_id` FOREIGN KEY (fk_user_id) REFERENCES User(id) ON DELETE CASCADE
);

schema.prisma模式棱镜

model Post {
  content    String?
  createdAt  DateTime @default(now())
  fk_user_id Int
  id         Int      @default(autoincrement()) @id
  published  Boolean  @default(false)
  title      String
  author     User     @relation(fields: [fk_user_id], references: [id])

  @@index([fk_user_id], name: "fk_user_id")
}

model User {
  email    String   @unique
  id       Int      @default(autoincrement()) @id
  name     String?
  password String   @default("")
  Post     Post[]
  Profile  Profile?
}

You are violating the foreign key constraint between Post and User .您违反了PostUser之间的外键约束。 You can not remove a User before deleting its Posts在删除用户的Posts之前,您不能删除User

beforeEach(async () => {
    const prisma = new PrismaClient()
    await prisma.post.deleteMany({where: {...}}) //delete posts first
    await prisma.user.deleteMany({})
})

Or set CASCADE deletion on the foreign key , this way when you delete a User its posts will be automatically deleted或者在外键上设置 CASCADE 删除,这样当你删除一个用户时,它的帖子会被自动删除

This is another way to do it, this would remove all rows and its dependant rows, also would reset the ids.这是另一种方法,这将删除所有行及其相关行,也会重置 ID。 This way you can iterate over all the tables and order doesn't matter.通过这种方式,您可以遍历所有表并且顺序无关紧要。

prisma.$executeRaw(`TRUNCATE TABLE ${table} RESTART IDENTITY CASCADE;`)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM