首页 > 解决方案 > TypeORM:订阅两个模型

问题描述

嗨,我一直在使用 TypeORM,但在订阅两个模型时遇到问题,动作......我想听听两个模型的变化,而不仅仅是一个

我有 2 个模型用户和帖子我如何收听这两个模型的更新

import { EntitySubscriberInterface, EventSubscriber, InsertEvent, UpdateEvent } from 'typeorm';
import { User } from '../users/user.entity';

@EventSubscriber()
export class HistorySubscriber implements EntitySubscriberInterface<User> {

    listenTo() {
        return User; // here i would like to listen also to post Updates
    }


    /**
     * Called after User update.
     */
    async afterUpdate(event: UpdateEvent<User>) {
        const newValue = event.entity;

    }

}

标签: postgresqlsequelize.jstypeorm

解决方案


AEntitySubscriberInterface只能听

  • 恰好是一个实体或
  • 对任何(所有)实体

有关示例,请参阅文档。如果您查看TypeORM 中评估的相应代码行listenTo(),则应该也可以过滤实体类的父类。

subscriber.listenTo().isPrototypeOf(target);

因此,如果UserPost实体类继承自同一个父类,则应该可以用一个订阅者订阅这两个类。


推荐阅读