繁体   English   中英

TypeORM:OneToOne 与 OneToMany 在同一实体上

[英]TypeORM: OneToOne with OneToMany on same Entity

我有 2 个实体,我希望它们以 2 种方式相互关联。 我将把它表示为 Class 和学生。 我希望所有学生都属于一个 Class 但我希望 Class 不仅有很多学生,而且还有一个 class 总统。 实体现在看起来像这样:

@Entity()
export class Class extends BaseEntity {
  @PrimaryGeneratedColumn("uuid")
  id: string

  @OneToOne(type => Student, { nullable: true })
  @JoinColumn({ name: "classPresident", referencedColumnName: "id" })
  classPresident?: Student

  @OneToMany(type => Student, (student) => student.class, { nullable: true })
  students?: Student[]
}

@Entity()
export class Student extends BaseEntity {
  @PrimaryGeneratedColumn("uuid")
  id: string

  @ManyToOne(() => Class, (c) => c.students)
  class?: Class
}

这不符合我的预期。 我希望 Class 表使用列classPresident创建,该列是学生的关键。 我希望不必自己做钥匙,欢迎任何批评。

我希望 Class 表使用列 classPresident 创建,该列是学生的关键。

我无法重现您的问题。 当我使用您的实体时,您所期望的正是发生的事情。

这是 typeorm 记录的内容:

query: CREATE TABLE "class" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "classPresident" uuid, CONSTRAINT "REL_ba4e89afdc05df2bda1c2c532c" UNIQUE ("classPresident"), CONSTRAINT "PK_0b9024d21bdfba8b1bd1c300eae" PRIMARY KEY ("id"))
creating a new table: public.student
query: CREATE TABLE "student" ("id" uuid NOT NULL DEFAULT uuid_generate_v4(), "classId" uuid, CONSTRAINT "PK_3d8016e1cb58429474a3c041904" PRIMARY KEY ("id"))
creating a foreign keys: FK_ba4e89afdc05df2bda1c2c532c2 on table "class"
query: ALTER TABLE "class" ADD CONSTRAINT "FK_ba4e89afdc05df2bda1c2c532c2" FOREIGN KEY ("classPresident") REFERENCES "student"("id") ON DELETE NO ACTION ON UPDATE NO ACTION
creating a foreign keys: FK_bd5c8f2ef67394162384a484ba1 on table "student"
query: ALTER TABLE "student" ADD CONSTRAINT "FK_bd5c8f2ef67394162384a484ba1" FOREIGN KEY ("classId") REFERENCES "class"("id") ON DELETE NO ACTION ON UPDATE NO ACTION

这是创建的结构的屏幕截图: 表类的结构

编辑:我的 package.json:

{
   "name": "typeorm-nodejs-demo",
   "version": "0.0.1",
   "description": "Awesome project developed with TypeORM.",
   "type": "commonjs",
   "devDependencies": {
      "@types/node": "^16.11.10",
      "ts-node": "10.7.0",
      "typescript": "4.5.2"
   },
   "dependencies": {
      "dotenv": "^16.0.1",
      "pg": "^8.4.0",
      "reflect-metadata": "^0.1.13",
      "typeorm": "0.3.7"
   },
   "scripts": {
      "start": "ts-node src/index.ts",
      "typeorm": "typeorm-ts-node-commonjs"
   }
}

我的 tsconfig.json:

{
   "compilerOptions": {
      "lib": [
         "es5",
         "es6"
      ],
      "target": "es2020",
      "module": "commonjs",
      "moduleResolution": "node",
      "outDir": "./build",
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "sourceMap": true
   }
}

要使用extends BaseEntity ,我必须将每个实体拆分为自己的文件。

暂无
暂无

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

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