使用 Prisma 5 和 JavaScript 建立关系时出错

问题描述 投票:0回答:1

我正在尝试为我的 prisma 数据库播种,但在用户 -> 付款关系方面遇到困难。

播种者代码:

export const userSeeder = async (prisma) => {
  const productIds = await getProductIds(prisma);
  const {
    gamingLaptopProductId,
    chairProductId,
    cologneProductId,
  } = productIds;

  console.log(chalk.blue('ABOUT TO RUN BOBBYS SEEDER'));
  const bobby = await prisma.user.upsert({
    where: { email: '[email protected]' },
    update: {},
    create: {
      username: 'bobby',
      email: '[email protected]',
      password: 'bob123',
      first_name: 'Bob',
      last_name: 'Brown',
      role: 'ADMIN',
      created_at: new Date().toISOString(),
      updated_at: new Date().toISOString(),
      deleted: false,
      UserAddress: {
        create: [
          {
            address_type: 'Shipping',
            address: {
              create: {
                address_type: 'Shipping',
                street_address: '123 Fake Street',
                city: 'New York',
                state: 'NY',
                zip_code: '12345',
                country: 'USA',
                created_at: new Date().toISOString(),
                updated_at: new Date().toISOString(),
                deleted: false,
              },
            },
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
            deleted: false,
          },
          {
            address_type: 'Billing',
            address: {
              create: {
                address_type: 'Billing',
                street_address: '742 Evergreen Terrace',
                city: 'Springfield',
                state: 'OR',
                zip_code: '99898',
                country: 'USA',
                created_at: new Date().toISOString(),
                updated_at: new Date().toISOString(),
                deleted: false,
              },
            },
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
            deleted: false,
          },
        ],
      },
      comments: {
        create: [
          {
            product_id: gamingLaptopProductId,
            content: 'This is a great Laptop!',
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
            deleted: false,
          },
          {
            product_id: tshirtProductId,
            content: 'Such a nice shirt',
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
            deleted: false,
          },
        ],
      },
      ratings: {
        create: [
          {
            product_id: cologneProductId,
            rating: 5,
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
            deleted: false,
          },
          {
            product_id: tshirtProductId,
            rating: 3,
            created_at: new Date().toISOString(),
            updated_at: new Date().toISOString(),
            deleted: false,
          },
        ],
      },
    },
  });

  if (bobby) {
    console.log(chalk.green('Bobby was created successfully.'));

    await prisma.payment.create({
      data: {
        user: bobby,
        payment_method: 'Credit Card',
        exp_month: 0o1,
        exp_year: 2026,
        card_number: '1233-4567-8901-2292',
        payment_status: 'PENDING',
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
        deleted: false,
        Order: {
          create: [
            {
              status: 'Shipped',
              total_price: 41.5,
              created_at: new Date().toISOString(),
              updated_at: new Date().toISOString(),
              deleted: false,
              OrderItem: {
                create: [
                  {
                    product_id: chairProductId,
                    quantity: 1,
                    price: 35.99,
                    created_at: new Date().toISOString(),
                    updated_at: new Date().toISOString(),
                    deleted: false,
                  },
                ],
              },
            },
          ],
        },
      },
    });

    console.log(chalk.green('Payment was created successfully.'));
  } else {
    console.error(chalk.red('Bobby was not found.'));
  }

  console.log('[Users w/ Addresses, Orders, Reviews, and Comments seeded successfully]');
};

相关 Prisma 型号:

model User {
  id          String        @id @default(uuid())
  username    String        @unique
  email       String        @unique
  password    String
  first_name  String
  last_name   String?
  created_at  DateTime      @default(now())
  updated_at  DateTime      @updatedAt
  deleted     Boolean       @default(false)
  role        String        @default("USER")
  comments    Comment[]
  ratings     Rating[]
  orders      Order[]
  UserAddress UserAddress[]
  payments    Payment[]
}


model Payment {
  id             String   @id @default(uuid())
  user           User     @relation(fields: [user_id], references: [id])
  user_id        String // Change type to String
  payment_method String // Mock payment method (e.g., "credit card")
  exp_month      Int? // Optional, month of expiration (e.g., 1 for January)
  exp_year       Int? // Optional, year of expiration (e.g., 2024)
  card_number    String? // Optional, masked card number (e.g., "XXXX XXXX XXXX XXXX")
  payment_status String   @default("PROCESSED") // Mock payment status (e.g., "success", "failure")
  created_at     DateTime @default(now())
  updated_at     DateTime @updatedAt
  deleted        Boolean  @default(false)
  Order          Order[]
}

model Order {
  id          String      @id @default(uuid())
  user        User        @relation(fields: [user_id], references: [id])
  user_id     String
  status      String
  total_price Float
  payment     Payment     @relation(fields: [payment_id], references: [id])
  payment_id  String
  created_at  DateTime    @default(now())
  updated_at  DateTime    @updatedAt
  deleted     Boolean     @default(false)
  OrderItem   OrderItem[]
}

model OrderItem {
  id         String   @id @default(uuid())
  order      Order    @relation(fields: [order_id], references: [id])
  order_id   String // Field will exist in db
  product    Product  @relation(fields: [product_id], references: [id])
  product_id String // Field will exist in db
  quantity   Int
  price      Float
  created_at DateTime @default(now())
  updated_at DateTime @updatedAt
  deleted    Boolean  @default(false)
}

所有其他关系(评论、评分等...)都已正确创建,我只是在用户上创建

payments
时遇到问题。

如果我运行

npx prisma migrate reset
,这就是我得到的错误:

ABOUT TO RUN BOBBYS SEEDER
Bobby was created successfully.
PrismaClientValidationError: 
Invalid `prisma.payment.create()` invocation:

{
  data: {
    user: {
      id: "81e533bf-dc27-4b1f-89a1-44384dfa13b1",
      ~~
      username: "bobby",
      email: "[email protected]",
      password: "bob123",
      first_name: "Bob",
      last_name: "Brown",
      created_at: new Date("2024-05-06T14:35:34.112Z"),
      updated_at: new Date("2024-05-06T14:35:34.112Z"),
      deleted: false,
      role: "ADMIN",
?     create?: UserCreateWithoutPaymentsInput | UserUncheckedCreateWithoutPaymentsInput,
?     connectOrCreate?: UserCreateOrConnectWithoutPaymentsInput,
?     connect?: UserWhereUniqueInput
    },
    payment_method: "Credit Card",
    exp_month: 1,
    exp_year: 2026,
    card_number: "1233-4567-8901-2292",
    payment_status: "PENDING",
    created_at: "2024-05-06T14:35:34.117Z",
    updated_at: "2024-05-06T14:35:34.117Z",
    deleted: false,
    Order: {
      create: [
        {
          status: "Shipped",
          total_price: 41.5,
          created_at: "2024-05-06T14:35:34.117Z",
          updated_at: "2024-05-06T14:35:34.117Z",
          deleted: false,
          OrderItem: {
            create: [
              {
                product_id: "581b8e88-080f-4d04-a55d-9db52d4be97a",
                quantity: 1,
                price: 35.99,
                created_at: "2024-05-06T14:35:34.117Z",
                updated_at: "2024-05-06T14:35:34.117Z",
                deleted: false
              }
            ]
          }
        }
      ]
    }
  }
}

Unknown argument `id`. Available options are marked with ?.

所以很自然地,我尝试在创建之前删除

id
,但随后它会抛出有关用户名、电子邮件等的相同错误...如果我尝试仅通过
user_id
,它会说
missing property user
...这是为什么我要传递整个鲍比用户。

我不知道如何进行这项工作......任何想法都会有帮助。谢谢!

javascript database-design prisma seeding
1个回答
0
投票

您需要将

user
对象替换为
user_id

if (bobby) {
    console.log(chalk.green('Bobby was created successfully.'));

    
    await prisma.payment.create({
      data: {
        user_id: bobby.id, // Use only the user's ID
        payment_method: 'Credit Card',
        exp_month: 1,
        exp_year: 2026,
        card_number: '1233-4567-8901-2292',
        payment_status: 'PENDING',
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString(),
        deleted: false,
        Order: {
          create: [
            {
              status: 'Shipped',
              total_price: 41.5,
              created_at: new Date().toISOString(),
              updated_at: new Date().toISOString(),
              deleted: false,
              OrderItem: {
                create: [
                  {
                    product_id: chairProductId,
                    quantity: 1,
                    price: 35.99,
                    created_at: new Date().toISOString(),
                    updated_at: new Date().toISOString(),
                    deleted: false,
                  },
                ],
              },
            },
          ],
        },
      },
    });

    console.log(chalk.green('Payment was created successfully.'));
} else {
    console.error(chalk.red('Bobby was not found.'));
}
© www.soinside.com 2019 - 2024. All rights reserved.