问题
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 NULL
s.
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