Prisma 一对多关系插入和更新

时间:2021-06-07 15:45:44

标签: relationship prisma

型号

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

generator client {
  provider = "prisma-client-js"
}

generator dbml {
  provider = "prisma-dbml-generator"
}

model Inventory {
  id        Int       @id @default(autoincrement())
  userId    String    @map("user_id")
  type      String    @unique
  currency  String
  active    String    @default("Y")
  createdAt DateTime  @default(now()) @map("created_at")
  updatedAt DateTime? @default(now()) @map("updated_at")
  createdBy String?   @map("created_by")
  updatedBy String?   @map("updated_by")
  products  Product[]

  @@map("inventory")
}

model Category {
  id             Int       @id @default(autoincrement())
  categoryName   String    @unique@map("category_name")
  categoryConfig String    @map("category_config")
  categoryType   String    @default("SERVICE") @map("category_type")
  createdAt      DateTime  @default(now()) @map("created_at")
  updatedAt      DateTime  @default(now()) @map("updated_at")
  createdBy      String?   @map("created_by")
  updatedBy      String?   @map("updated_by")
  products       Product[]
}

model Product {
  id                           Int        @id @default(autoincrement())
  categories                   Category?  @relation(fields: [categoryId], references: [id])
  inventories                  Inventory? @relation(fields: [inventoryId], references: [id])
  categoryId                   Int?       @map("category_id")
  inventoryId                  Int?       @map("inventoryId")
  productName                  String     @unique @map("product_name")
  productDescription           String     @map("product_description")
  productUnitPrice             Float      @map("product_unit_price")
  productUnitOfMeasure         Int?       @map("product_unit_of_measure")
  productInStock               Int?       @map("product_in_stock")
  productStatus                Boolean    @default(true) @map("product_status")
  productSize                  Float?     @map("product_size")
  productColour                String?    @map("product_colour")
  productModel                 String?    @map("product_model")
  productSlug                  String?    @map("product_slug")
  productAvatar                String?    @map("product_avatar")
  productDeliveryCharges       Int?       @map("product_delivery_charges")
  productDeliveryFrequencyRate Int        @map("product_delivery_frequency_rate")
  productAverageRating         Int?       @map("product_average_rating")
  createdAt                    DateTime?  @default(now()) @map("created_at")
  updatedAt                    DateTime?  @map("updated_at")
  createdBy                    String?    @map("created_by")
  updatedBy                    String?    @map("updated_by")

  @@map("products")
}

库存DTO

 export class InventoryDTO {
      @ApiProperty() @IsNotEmpty() readonly userId: string;
      @ApiProperty() @IsNotEmpty() readonly type: string;
      @ApiProperty() @IsNotEmpty() readonly currency: string;
      @ApiProperty() readonly products: prisma.ProductCreateNestedManyWithoutInventoriesInput;
    }

控制器:

@Post('add')
  async addInventory(
    @Body() inventoryDTO: InventoryDTO,
  ): Promise<InventoryEntity> {
    let data = this.inventoryService.addInventory(inventoryDTO);
    let result = await data.then((result) => {
      return classToClass(new InventoryEntity(result));
    });
    return result;
  }

服务

async addInventory(data: Prisma.InventoryCreateInput): Promise<Inventory> {
    let recordExists = this.getInventory({ type: data.type });
    let result = await recordExists.then((result) => {
      return result;
    });

    if (result == null) {
      return this.prismaService.inventory.create({
        data,
        include: {
          products: true,
        },
      });
    } else {
      this.logger.error(ERROR_INVENTORYTYPE_MUST_BE_UNIQUE);
      throw new HttpException(
        ERROR_INVENTORYTYPE_MUST_BE_UNIQUE,
        HttpStatus.BAD_REQUEST,
      );
    }
  }

我附上了我的所有代码,当我尝试从多个产品的 UI 发送inventyDTO 中的数据时。如下图

{
...InventoryData,
...products : [{
         }]
}

我想通过 addInventory 方法在库存和产品表中插入记录。有人请帮忙处理这个请求。??

仅供参考,Prisma 生成以下模型,

Prisma.InventoryCreateInput

  export type InventoryCreateInput = {
    type: string
    currency: string
    active?: string
    userId: string
    createdAt?: Date | string
    updatedAt?: Date | string | null
    createdBy?: string | null
    updatedBy?: string | null
    products?: ProductCreateNestedManyWithoutInventoriesInput
  }


export type ProductCreateNestedManyWithoutInventoriesInput = {
create?: XOR<Enumerable<ProductCreateWithoutInventoriesInput>, Enumerable<ProductUncheckedCreateWithoutInventoriesInput>>
connectOrCreate?: Enumerable<ProductCreateOrConnectWithoutInventoriesInput>
createMany?: ProductCreateManyInventoriesInputEnvelope
connect?: Enumerable<ProductWhereUniqueInput>

}

1 个答案:

答案 0 :(得分:1)

您的数据应如下所示:

const data: Prisma.InventoryCreateInput = {
    currency: 'c',
    type: 't',
    userId: 'u',
    products: {
      create: [
        {
          productDeliveryFrequencyRate: 1,
          productName: 'p',
          productDescription: 'd',
          productUnitPrice: 1,
        },
      ],
    },
}

您可以通过转到 ProductCreateNestedManyWithoutInventoriesInput 的定义并查看它接受的内容来查看输入。