首页 > 解决方案 > 正确使用 IdentifiedReference 和 { WrappedReference: true }

问题描述

有了这个,我不理解它,我不想污染原始问题。我需要一直{ wrappedReference: true }使用IdentifiedReference吗?

因为,这失败了:

@Entity({ collection: "account" })
export class AccountEntity implements IdEntity<AccountEntity> {
    @PrimaryKey()
    public id!: number;

    @OneToOne(() => ArtistEntity, "account", { wrappedReference: true })
    public artist!: IdentifiedReference<ArtistEntity>;
}

@Entity({ collection: "artist" })
export class ArtistEntity implements IdEntity<ArtistEntity> {
    @PrimaryKey()
    public id!: number;

    @OneToOne(() => AccountEntity, { wrappedReference: true })
    public account!: IdentifiedReference<AccountEntity>;
}

和:

src/entities/artistEntity.ts(15,38): error TS2345: Argument of type '{ WrappedReference: boolean; }' 不能分配给“id”类型的参数 | “名字” | “密码” | “电子邮件” | “形象” | “艺术家” | “收藏” | “工作室” | ((e:AccountEntity)=>任何)| 不明确的'。对象字面量只能指定已知属性,并且类型“(e:AccountEntity)=> any”中不存在“wrappedReference”。

那么,这会正确吗?

@Entity({ collection: "account" })
export class AccountEntity implements IdEntity<AccountEntity> {
    @PrimaryKey()
    public id!: number;

    @OneToOne(() => ArtistEntity, "account", { wrappedReference: true })
    public artist!: IdentifiedReference<ArtistEntity>;
}

@Entity({ collection: "artist" })
export class ArtistEntity implements IdEntity<ArtistEntity> {
    @PrimaryKey()
    public id!: number;

    @OneToOne(() => AccountEntity)
    public account!: IdentifiedReference<AccountEntity>;
}

标签: mikro-orm

解决方案


问题是您正在尝试将@OneToOne装饰器的第二个参数用于选项对象,但目前仅支持第一个或第三个参数

// works if you use the default `TsMorphMetadataProvider`
@OneToOne()
public account!: IdentifiedReference<AccountEntity>;

// use first param as options
@OneToOne({ entity: () => AccountEntity, wrappedReference: true })
public account!: IdentifiedReference<AccountEntity>;

// use third param as options
@OneToOne(() => AccountEntity, undefined, { wrappedReference: true })
public account!: IdentifiedReference<AccountEntity>;

// you can also do this if you like
@OneToOne(() => AccountEntity, 'artist', { owner: true, wrappedReference: true })
public account!: IdentifiedReference<AccountEntity>;

但这会在最终的 v3 版本之前改变,所以如果你使用TsMorphMetadataProvider(默认的),即使没有显式的wrappedReference: true.

这是您可以订阅的关于即将发生的更改的问题:https ://github.com/mikro-orm/mikro-orm/issues/265

(这是关于可空性,但这是此更改的另一个副作用)


推荐阅读