Nest.js-在实体中定义OneToMany关系

时间:2020-07-09 12:17:13

标签: node.js typescript one-to-many nestjs typeorm

我在NestJS项目中定义实体字段。我有成功定义的ManyToOne构型。我很难找到正确的方法来定义OneToMany关系以适合我用于其他关系的语法。

import {Entity,Column, PrimaryColumn, ManyToOne,JoinColumn,OneToMany} from "typeorm";
import { Account } from "./account.entity";
import { Balance } from "./balance.entity";
import { BaseEntity } from "./base.entity";

@Entity()
export class MainEntity extends BaseEntity {
  @PrimaryColumn({
    type: "varchar",
    name: "id",
    unique: true
  })
  id: string;

  @ManyToOne(() => Account, { nullable: true })
  @JoinColumn({
    name: "account_id",
    referencedColumnName: "id"
  })
  account: Account;

@OneToMay关系需要连接到Balance实体,并在其中映射了ByPypayDevice字段。

我的尝试:

@OneToMany(() => Balance, ...)
balances: Balance[]

我在NestJs和打字稿中,所以这对我来说是个挑战。

1 个答案:

答案 0 :(得分:1)

通常,NestJS中使用的TypeORM关系简单且易于开发。您编写的代码定义了已经预定义的参数。 例如,

@PrimaryColumn({
    type: "varchar",
    name: "id",
    unique: true
  })

确切的参数是由

定义的
@PrimaryColumn() // unique: true
id: string //varchar, name: id

因此,您可以像下面这样获得代码。对于帐户实体,

@Entity()
export class Account {

    @PrimaryColumn()
    id: string;


    @ManyToOne(type => Balance, balance => balance.id)
    balance: Balance;

}

对于余额实体

@Entity()
export class Balance {

   @PrimaryColumn()
   id: string;


   @OneToMany(type => Account, account => account.id)
   @JoinColumn({name: "account_id"})   
   // defining this is also optional because by default,
   // the referenced foreign key is named as <column_name>_id or account_id

   account: Account;

}

这将在Account帐户和OneToMany on Balance实体上创建多对一关系。有关更多此类示例,请参见:https://orkhan.gitbook.io/typeorm/docs/many-to-one-one-to-many-relations