英文:
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 数字。- 不需要同时指定
type
和columnType
,当你在其中提供相同的值时。 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 tostring
, notnumber
, as you can't fit a double into JS number- no need to specify
type
andcolumnType
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 withCascade.REMOVE
) will be removed too - this is the opposite ofonDelete: 'cascade'
, which I guess you want instead (so when the target is removed - theCsgoItem
entity - the owner (soCase
) will be removed too
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论