问题:Prisma prisma introspect 为外键返回奇怪的值

我有两张桌子,UserRelationship。这些表用于存储父子关系。我正在使用Postgres

// schema.sql

CREATE TABLE "public"."Relationships" (
    id SERIAL PRIMARY KEY NOT NULL,
    parent_id INT NOT NULL,
    FOREIGN KEY (parent_id) REFERENCES "User" (id),
    child_id INT NOT NULL,
    FOREIGN KEY (child_id) REFERENCES "User" (id)
)

CREATE TABLE "public"."User" (
    id SERIAL PRIMARY KEY NOT NULL,
    name VARCHAR(128) NOT NULL,
    email VARCHAR(128) UNIQUE,
    password VARCHAR(128) NOT NULL,
    isChild BOOLEAN NOT NULL DEFAULT false
    created_at TIMESTAMP NOT NULL DEFAULT NOW();
);  

当我运行npx prisma introspect时,schema.prisma文件中会返回以下内容。

// schema.prism

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

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

model Relationships {
  child_id                           Int
  id                                 Int  @default(autoincrement()) @id
  parent_id                          Int
  User_Relationships_child_idToUser  User @relation("Relationships_child_idToUser", fields: [child_id], references: [id])
  User_Relationships_parent_idToUser User @relation("Relationships_parent_idToUser", fields: [parent_id], references: [id])
}

model User {
  created_at                                  DateTime        @default(now())
  email                                       String?         @unique
  id                                          Int             @default(autoincrement()) @id
  ischild                                     Boolean         @default(false)
  name                                        String?
  password                                    String
  Relationships_Relationships_child_idToUser  Relationships[] @relation("Relationships_child_idToUser")
  Relationships_Relationships_parent_idToUser Relationships[] @relation("Relationships_parent_idToUser")
}

我不明白User_Relationships_child_idToUserUser_Relationships_parent_idToUser是什么以及为什么它们不仅仅是 Prisma 文档教程中外键出现的简单语法。

解答

Prisma 的自省为每个外键生成两个字段:

  • relation scalar field(基本上是外键的直接表示)

  • relation field(使用@relation属性注释)——这些字段似乎让您感到困惑。它们提供的原因是您可以在 Prisma Client API 中轻松处理关系。

您可以在此处的文档中找到更多信息。

当然User_Relationships_parent_idToUserUser_Relationships_child_idToUser不是很好听的名字。您可以在自省后手动调整架构,并将重命名关系字段以具有更友好的名称,例如:

model Relationships {
  child_id  Int
  id        Int  @default(autoincrement()) @id
  parent_id Int
  child     User @relation("Relationships_child_idToUser", fields: [child_id], references: [id])
  parent    User @relation("Relationships_parent_idToUser", fields: [parent_id], references: [id])
}
Logo

PostgreSQL社区为您提供最前沿的新闻资讯和知识内容

更多推荐