What is the correct way how to create relation in typeorm?

我是研究僧i 提交于 2020-12-26 12:17:55

问题


I have two entities:

@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 object already exist in database and I would like to create item with realtion to provider.

My code is:

        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;

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?


Generic entity class contains only id

@PrimaryGeneratedColumn('uuid')
id: string;

回答1:


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 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);



回答2:


Thanks to @alex-wayne who pointed out this question to me. For Reference, the approach which he proposed most likely originated from this github issue. More precisely this answer from pleerock, the core contributor.

Moreover, I personally prefer the first approach. In practice, with the addition to using the create method:

const content = 'mockContent';
const providerId = '5be045b1-ef49-4818-b69f-a45c0b7e53';

const provider = new Provider();
provider.id = providerId;
       
const item = this.itemRepository.craete({ content, provider })

await this.repository.save(item);


来源:https://stackoverflow.com/questions/64722060/what-is-the-correct-way-how-to-create-relation-in-typeorm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!