Mikro ORM 的 unique 装饰器在不被执行时

huangapple go评论62阅读模式
英文:

Mikro ORM unique decorator is not being enforced when

问题

使用这个实体:

@Entity()
@Unique({ properties: ['case', 'csgoItem'] })
export class CaseItem {
  @PrimaryKey({ type: 'uuid', defaultRaw: 'uuid_generate_v4()' })
  id: string;

  @Property({ type: 'double precision', columnType: 'double precision' })
  probability: number;

  @ManyToOne(() => Case)
  case!: Case;

  @ManyToOne(() => CsgoItem, { cascade: [Cascade.REMOVE] })
  csgoItem!: CsgoItem;
}

当尝试插入重复项(基于 case 和 csgItem 的组合)时,mikroORM 允许我这样做。如何使@unique装饰器与关系一起工作?

英文:

Using this entity:

@Entity()
@Unique({ properties: ['case', 'csgoItem'] })
export class CaseItem {
  @PrimaryKey({ type: 'uuid', defaultRaw: 'uuid_generate_v4()' })
  id: string;

  @Property({ type: 'double precision', columnType: 'double precision' })
  probability: number;

  @ManyToOne(() => Case)
  case!: Case;

  @ManyToOne(() => CsgoItem, { cascade: [Cascade.REMOVE] })
  csgoItem!: CsgoItem;
}

When trying to insert a duplicate (based on the combination of case and csgItem, mikroORM allows me to do this. How can I make the @unique decorator work with relations?

答案1

得分: 0

这是一个模式特性,ORM 不会强制执行它,所以你可能有不同步的模式 - 换句话说,唯一约束未创建。

尝试运行 npx mikro-orm schema:update --run,或者更好的是,如果这不仅仅是一个玩具项目,采用迁移。

关于你提供的代码有几点注意事项:

  • probability 是 double 类型,所以它将被映射为 string,而不是 number,因为你不能将 double 映射到 JS 数字。
  • 不需要同时指定 typecolumnType,当你在其中提供相同的值时。
  • cascade: [Cascade.REMOVE] 可能不是你想要的,这是应用级联动,意味着当你删除拥有的实体(CaseItem)时,其关系(标记为 Cascade.REMOVE 的关系)也将被删除 - 这与 onDelete: 'cascade' 相反,我猜你可能想要这个(所以当目标被删除 - CsgoItem 实体 - 所有者(即 Case)也将被删除)。
英文:

This is a schema feature, the ORM does not enforce it anyhow, so you probably have out-of-sync schema - in other words, the unique constraint is not created.

Try running npx mikro-orm schema:update --run, or even better, adopt migrations if it's something more than just a toy project.

Few notes about the code you provided:

  • probability is double, so it will be mapped to string, not number, as you can't fit a double into JS number
  • no need to specify type and columnType together, not when you provide the same value in there
  • the cascade: [Cascade.REMOVE] is probably not doing what you think, that is app-level cascading and means that when you delete the owning entity (CaseItem), its relations (marked with Cascade.REMOVE) will be removed too - this is the opposite of onDelete: 'cascade', which I guess you want instead (so when the target is removed - the CsgoItem entity - the owner (so Case) will be removed too

huangapple
  • 本文由 发表于 2023年5月20日 21:35:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76295508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定