Mikro-ORM 有没有办法在不加载引用实体的情况下加载子对象中的复合外键 ID?

时间:2021-04-08 18:32:19

标签: mikro-orm

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

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?

0 个答案:

没有答案