Saving and working with a self-referencing entity in typeorm

折月煮酒 提交于 2020-06-16 17:14:10

问题


I will try to be clear when explaining the issue I'm currently facing.

A piece of code from the CategoryEntity class.

category.entity.ts

    @ManyToMany(type => EntryEntity, entry => entry.categories)
    entries: EntryEntity[];

    @ManyToOne(type => UserEntity, user => user.categories, {onDelete: 'CASCADE', cascade: true})
    user: UserEntity;

    @ManyToOne(type => CategoryEntity, category => category.subcategories)
    category: CategoryEntity;

    @OneToMany(type => CategoryEntity, category => category.category)
    subcategories: CategoryEntity[];

I've learnt not so long ago that this is what's called a self-referecing (or decorated) entity.

Here is how I save a subcategory:

    public async createCategoryByUserId(userId: number, createCategoryDto: CreateCategoryDto): Promise<void> {
        const category = await this.categoryRepository.createQueryBuilder('category')
                                                      .where('category.user.id = :userId', {userId})
                                                      .andWhere('category.id = :id', {id: createCategoryDto.id})
                                                      .getOne();

        const subcategory = new CategoryEntity();
        subcategory.setName(createCategoryDto.name)
                   .setIsBaseTemplate(false)
                   .setSection(category.section);

        await this.categoryRepository.save(subcategory);

        const newCategory = new CategoryEntity();

        Object.assign(newCategory, category);

        const subcategories = (await this.categoryRepository.createQueryBuilder('category')
                                   .where('category.user.id = :userId', {userId})
                                   .andWhere('category.id = :id', {id: createCategoryDto.id})
                                   .leftJoinAndSelect('category.subcategories', 's')
                                   .getOne()).subcategories;

        newCategory.subcategories = [...subcategories, subcategory];

        await this.categoryRepository.save(newCategory);

The problem with this is that in the category table there ist a user id associated with each category but the subcategories are associated with categories, not users, their userIds are NULLs.

I'm trying to write a request that would return a category/subcategory by the user id and category/subcategory id. I think that would be easier if the subcategories had userIds associated with them. But is it possible?

Maybe I'm just saving it the wrong way, I'm new to typeorm, sorry.

来源:https://stackoverflow.com/questions/62314903/saving-and-working-with-a-self-referencing-entity-in-typeorm

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