【问题标题】:Nestjs - define OneToMany relation in entityNestjs - 在实体中定义 OneToMany 关系
【发布时间】:2020-07-14 17:21:54
【问题描述】:

我在我的 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 实体并在其中 mappedBy paymentDevice 字段。

我的尝试:

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

我在 NestJs 和 typescript 中,所以这对我来说很有挑战性。

【问题讨论】:

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


    【解决方案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 上创建多对一关系,在 Balance 实体上创建 OneToMany。更多此类示例,请参考:https://orkhan.gitbook.io/typeorm/docs/many-to-one-one-to-many-relations

    【讨论】:

      猜你喜欢
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      • 2020-06-15
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多