扩展多个类以包含来自其他实体的列在 nest JS 中不起作用

问题描述 投票:0回答:1

我正在做一个嵌套项目,我必须在其中扩展我的实体类以具有来自其他类的公共列。 基础模型

import { Index, PrimaryGeneratedColumn } from "typeorm";

export class BaseModel {
    @PrimaryGeneratedColumn('uuid')
    id: string
}

审计模型

import { Exclude } from "class-transformer";
import { RequestContext } from "src/utils/req-ctx";
import { BeforeInsert, BeforeUpdate, Column, CreateDateColumn, DeleteDateColumn, PrimaryGeneratedColumn, UpdateDateColumn } from "typeorm";

export class AuditModel {

    @Column({ name: "created_by", default: null })
    created_by: string

    @Column({ name: "modified_by", default: null })
    modified_by: string


    @BeforeInsert()
    setAuditsBeforeInsert() {
        console.log(RequestContext.currentRequest)
        if (RequestContext.currentRequest.currentUser) {
            this.created_by = this.modified_by = RequestContext.currentRequest.currentUser.name
        }
    }

    @BeforeUpdate()
    setAuditsBeforeUpdate() {
        if (RequestContext.currentRequest.currentUser) {
            this.modified_by = RequestContext.currentRequest.currentUser.name
        }
    }
}

用户模型

import { BaseModel } from 'src/base-models/base-model';
import { AuditModel } from 'src/base-models/audit-model';

function mixin(...classes: any[]): any {
  class MixedClass {}

  classes.forEach((clazz) => {
    Object.getOwnPropertyNames(clazz.prototype).forEach((name) => {
      MixedClass.prototype[name] = clazz.prototype[name];
    });
  });

  return MixedClass;
}

@Entity()
@Unique(['email'])
export class Users extends mixin(BaseModel,AuditModel) {
//Other user attributes
}

我正在尝试这种方法,我想要它以同样的方式,因为还有一些其他模型用基本模型扩展了一些其他模式。

任何人都可以帮我让它工作吗?

node.js typescript nestjs typeorm nest
1个回答
0
投票

您可以轻松扩展实体,

baseClass
的列将由
childClass
继承,如下所示:

export class MultiTenantEntity
{
  @ManyToOne(() => Tenant, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'tenant_id' })
  tenant: Tenant;
  @Column({ name: 'tenant_id', type: 'uuid' })
  tenantId: string;
}
    
@Entity()
export class Product extends MultiTenantEntity {
  @Column({ length: 255 })
  name: string;
    
  @Column({ length: 255, nullable: true })
  description: string;
}
© www.soinside.com 2019 - 2024. All rights reserved.