首页 > 解决方案 > Mikro-ORM 中是否有一种方法可以在不加载引用实体的情况下在子对象中加载复合外键 ID?

问题描述

我有一个具有这种形状的对象:

import { Entity, IdentifiedReference, Index, ManyToOne, PrimaryKey, PrimaryKeyType, Reference } from '@mikro-orm/core';

import { AuditCreation } from './audit';
import { Program } from './program';
import { Role } from './role';
import { User } from './user';

@Entity()
export class UserRole extends AuditCreation {
  @ManyToOne({
    entity: () => User,
    inversedBy: (x) => x.userRoles,
    primary: true,
    wrappedReference: true,
    cascade: [],
    onUpdateIntegrity: 'no action',
    onDelete: 'cascade',
  })
  user: Reference<User>;

  @ManyToOne({
    entity: () => Role,
    inversedBy: (x) => x.userRoles,
    primary: true,
    wrappedReference: true,
    cascade: [],
    onUpdateIntegrity: 'no action',
    onDelete: 'no action',
  })
  role: IdentifiedReference<Role>;

  @ManyToOne({
    entity: () => Program,
    nullable: true,
    wrappedReference: true,
    cascade: [],
    onUpdateIntegrity: 'no action',
    onDelete: 'no action',
  })
  program: Reference<Program>;

  [PrimaryKeyType]: [string, string, string];

  constructor(value: Partial<UserRole> = {}) {
    super();
    Object.assign(this, value);
  }
}

用户和程序都使用复合主键(id + organization_id),因为我使用的是 postgresql 分区表。我找不到让 IdentifiedReference 适应复合主键的方法。它可能不受支持,因为em.getReference没有支持复合键 ( string[]) 并允许设置的方法签名wrapped: true。但我得到不一致的结果。

当我查询 User 并使用以下查询提取引用的 UserRole 时:

await this.em.findOneOrFail(
  User,
  { id: userId, organization: orgId },
  { populate: { userRoles: LoadStrategy.JOINED } },
);

当我序列化结果时,我为用户角色部分得到了这个:

{
    "user": {
        "id": "5a8edadb-3e4a-4073-a446-d59fcf1b317e",
        "organization": "2edbf460-550a-41e5-80b4-14eb0af22969"
    },
    "role": "program_admin",
    "program": null
}

所以它找到了一种方法来拉入用户和组织 ID,因为它们是主键的一部分,但它不会拉入程序 ID。我必须将程序添加到填充列表中,这会拉回整个程序对象,这出于性能原因是不可取的。

但是,如果我使用以下查询直接查询 UserRole:

await this.em.findOneOrFail(UserRole, { user: [userId, orgId] })

当我序列化结果时,参考就在那里:

{
    "user": {
        "id": "5a8edadb-3e4a-4073-a446-d59fcf1b317e",
        "organization": "2edbf460-550a-41e5-80b4-14eb0af22969"
    },
    "role": "program_admin",
    "program": {
        "id": "1a435277-03b9-4e7b-b96b-8ad3483ec7f6",
        "organization": "2edbf460-550a-41e5-80b4-14eb0af22969"
    }
}

Mikro-ORM 中是否有一种方法可以为子对象填充复合外键 ID,而无需加载不涉及加载引用实体的引用实体?

标签: mikro-orm

解决方案


推荐阅读