在typeorm中创建关系的正确方法是什么? [英] What is the correct way how to create relation in typeorm?
问题描述
我有两个实体:
@Entity({ name: 'provider' })
export class ProviderEntity extends GenericEntity {
@Column()
name: string;
@Column()
description: string;
@OneToMany(() => ItemEntity, item => item.provider)
items: Promise<ItemEntity[]>;
}
@Entity({ name: 'item' })
export class ItemEntity extends GenericEntity {
@Column()
content: string;
@ManyToOne(() => ProviderEntity, provider => provider.items)
provider: Promise<ProviderEntity>;
}
Provider
对象已经存在于数据库中,我想创建具有 provider
身份的 item
.
Provider
object already exist in database and I would like to create item
with realtion to provider
.
我的代码是:
const content = 'mockContent';
const providerId = '5be045b1-ef49-4818-b69f-a45c0b7e53';
const item = new ItemEntity();
item.content = content;
item.provider = providerId; // ERROR
await this.repository.save(item);
return item;
它可以工作,但是我遇到打字稿错误.类型'string'无法分配给'Promise< ProviderEntity>'类型.
.正确的插入方式是什么?
The code it works, but I am getting an typescript error Type 'string' is not assignable to type 'Promise<ProviderEntity>'.
. What is the correct way how to insert this?
通用实体类仅包含ID
Generic entity class contains only id
@PrimaryGeneratedColumn('uuid')
id: string;
推荐答案
我相信要通过关系ID(而不是完整的关系对象)来关联事物,您需要将关系ID添加到您的界面中:
I believe to associate things by a relation ID, and not a full relation object, you need to add the relation ID to your interface:
@ManyToOne(() => ProviderEntity, provider => provider.items)
provider: Promise<ProviderEntity>;
@Column()
providerId: string
providerId
是TypeORM用来在内部跟踪该关系的列,您只需要公开公开它即可.
providerId
is the column TypeORM uses to keep track of the relation internally, you simply simply need to expose it publicly.
然后您只需设置该属性:
And then you simply set that property:
const item = new ItemEntity();
item.content = content;
item.providerId = providerId; // set providerId column directly.
await this.repository.save(item);
这篇关于在typeorm中创建关系的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!