gpt4 book ai didi

node.js - TypeORM 实体继承多对一关系

转载 作者:行者123 更新时间:2023-12-04 12:50:34 25 4
gpt4 key购买 nike

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

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 关系时按预期工作:
@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
}

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

最佳答案

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

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

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

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;
}

然后使用它
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;
}

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

关于node.js - TypeORM 实体继承多对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54932600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com