首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >TypeORM实体继承ManyToOne关系

TypeORM实体继承ManyToOne关系
EN

Stack Overflow用户
提问于 2019-03-01 03:06:11
回答 1查看 2.7K关注 0票数 9

我在Node.JS中使用TypeORM,并希望使用实体继承来实现BaseRecord:

代码语言:javascript
代码运行次数:0
运行
复制
export abstract class BaseRecord {
  @CreateDateColumn({type: 'timestamp'})
  public created_at: Date;

  @UpdateDateColumn({type: 'timestamp'})
  public updated_at: Date;

  @ManyToOne(type => User, user => user.records_created)
  public created_by: User

  @ManyToOne(type => User, user => user.records_updated)
  public updated_by: User
}

我想通过它来扩展其他实体。当删除@ManyToOne关系时,这将按预期工作:

代码语言:javascript
代码运行次数:0
运行
复制
@Entity()
export class Address extends BaseRecord {
  @PrimaryGeneratedColumn()
  public id: number;

  @Column({ nullable: true, type: "text" })
  public alias: string;

  @Column({ type: "text" })
  public street_1: string;

  @Column({ nullable: true, type: "text" })
  public street_2: string;

  @Column({ type: "text" })
  public city: string;

  @Column({ type: "text" })
  public state: string;

  @Column({ type: "text" })
  public zip_code: string;

  @Column(type => GeoLocation)
  public geo_location: GeoLocation
}

有没有人遇到过这个或继承实体并拥有ManyToOne关系的方法?

EN

回答 1

Stack Overflow用户

发布于 2019-11-29 10:42:41

我建议在Embedded Entity中使用组合而不是继承

嵌入列是接受具有自己的列的类并将这些列合并到当前实体的数据库表中的列。

您可以根据需要在嵌入式类中使用任意数量的列(或关系)。您甚至可以在嵌入式类中嵌入嵌套的列。

代码语言:javascript
代码运行次数:0
运行
复制
import {Column} from "typeorm";

export class Assigned {
    @ManyToOne(type => User, user => user.records_created)
    public created_by: User

    @ManyToOne(type => User, user => user.records_updated)
    public updated_by: User
}

export class Dated {
    @CreateDateColumn({type: 'timestamp'})
    public created_at: Date;

    @UpdateDateColumn({type: 'timestamp'})
    public updated_at: Date;
}

然后使用它

代码语言:javascript
代码运行次数:0
运行
复制
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";
import {Assigned} from "./Assigned";
import {Dated} from "./Dated";

@Entity()
export class Address extends BaseRecord {
  // ...Other columns

  @Column(type => Assigned)
  assigned: Assigned;

  @Column(type => Dated)
  dated: Dated;
}

您可以根据需要在嵌入式类中使用任意数量的列(或关系)。您甚至可以在嵌入式类中嵌入嵌套的列。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54932600

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档