I am trying to solve a problem with the one-to-many relationship is not coming up when I query for it with both query builder and entity.
nest.js - 8.04 typeorm - 0.2.34
chapter.module.ts
@Module({
imports: [TypeOrmModule.forFeature([Chapter, ChapterRepository])],
controllers: [ChapterController],
providers: [ChapterService]
})
export class ChapterModule {}
chapter.entity.ts
@Entity()
export class Chapter {
@PrimaryGeneratedColumn()
id: number;
@Column()
transcript: string;
@Column()
translation: string;
@ManyToOne(type => Book, book => book.chapter)
book: Book;
@OneToMany(type => Paragraph, paragraph => paragraph.chapter)
paragraph: Paragraph[];
}
paragraph.module.ts
@Module({
imports: [TypeOrmModule.forFeature([Paragraph, ParagraphRepository])],
providers: [ParagraphService],
controllers: [ParagraphController]
})
export class ParagraphModule {}
paragraph.entity.ts
@Entity()
export class Paragraph {
@PrimaryGeneratedColumn()
id: number;
@Column({type: 'mediumtext'})
transcript: string;
@Column({type: 'mediumtext'})
translation: string;
@ManyToOne(type => Chapter , chapter => chapter.paragraph)
chapter: Chapter;
}
chapter table
-----------------------------------------
| id | transcript | translation | bookId |
|----------------------------------------|
| 1 | "Hello" | "Ola" | 1 |
------------------------------------------
paragraph table
---------------------------------------------
| id | transcript | translation | chapterId |
|-------------------------------------------|
| 1 | "Hello" | "Ola" | 1 |
| 2 | "One" | "Uno" | 1 |
---------------------------------------------
chapter.service.ts
async getOneChapter(chapterId: number): Promise<Chapter> {
try {
return await this.chapterRepository.findOne({
relations: ['paragraph'],
where: {id: chapterId},
})
} catch (error) {
throw new Error(error)
}
}
result:
{
id: 1,
transcript: "hello",
translation: "ola",
paragraph: []
}
paragraph should have 2 objects instead of an empty array. I tried query builder and gets the same result
paragraph.repository.ts
async getOneChapter(chapterId: number): Promise<Chapter> {
return this.createQueryBuilder('chapter')
.leftJoinAndSelect('chapter.paragraph', 'paragraph')
.where('chapter.id = :chapterId', {chapterId})
.getOne()
}