簡體   English   中英

如何更新 Nestjs 中具有“一對多”關系的 Prisma model

[英]How to update a Prisma model that has a relation "one-to-many" in Nestjs

我在 nestjs 中有這兩個 prisma 模型:

model DevInformations {
  userId      Int      @unique
  relatedUser User     @relation(fields: [userId], references: [id])
  name        String
  lastName    String
  dateOfBirth DateTime
  telNumber   String
  city        String
  zip         String
  country     String
  resume      String?
  links       Links[]
}

model Links {
  id          Int             @id @unique @default(autoincrement())
  userId      Int
  relatedUser DevInformations @relation(fields: [userId], references: [userId])
  name        String
  link        String
}

我對 create 方法沒有問題,但我找不到一種方法來更新鏈接字段,而不會 typescript 對我大喊大叫或出現 nestjs 錯誤。

我不明白更新此特定字段的步驟。

例如這里是我的代碼

const devInfo = await this.prisma.devInformations.update({
      where: {
        userId,
      },
      data: {
        ...rest,
        links: {
          create: [...dto.links],
        },
      },
      include: {
        links: true,
      },
    });

還有我的 DTO:

export class UpdateDevInfosDTO {
  @IsNumber()
  @IsNotEmpty()
  userId: number;

  ....All the fields,

  @IsArray()
  links: ILinkInput[];
}

export interface ILinkInput {
  id: number;
  name: string;
  link: string;
}

你得到什么樣的錯誤? 我成功地復制了 model,沒有出現任何錯誤,但是如果沒有上下文說明您究竟要對鏈接做什么,那么幫助不大。

*編輯:我看到您正在嘗試更改鏈接,但您的代碼專門嘗試更改DevInformations

嘗試更改鏈接,但改為指定相關的 DevInformations。

編寫的代碼有點類似於您要執行的操作。

// Find existing links that you want to update
const existingLinks = await this.prisma.links.findMany({
        where: {
          name: { // Can change to look for devInformations instead
            in: links.map((link) => link.name),
          },
        },
      });
    
// Map their names
const existingLinkNames = existingLinks.map((link) => link.name);
const linksToCreate = links.filter(
        (link) => !existingLinkNames.includes(link.name)
      );
const linksToUpdate = links.filter((hub) =>
        existingLinkNames.includes(link.name)
      );
const createdLinks = await this.prisma.links.createMany({
        data: linksToCreate.map((link) => ({
          name: link.name,
          // Connect with devInformations
          connect: {
              userId: devInfo.userId
          }
        })),
      });

// Perform same operations to match your use case
const updatedLinks = await this.prisma.links.updateMany({
        where: {
          name: {
            in: linksToUpdate.map((link) => link.name),
          },
        },
        data: {
          description: {
            set: linksToUpdate.map((link) => link.description),
          },
        },
      });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM