Rich
Rich

Reputation: 4248

TypeORM getRepository.find() does not include Foreign Key Fields

I am trying to fetch all the columns included on my entity, but I only able to fetch the columns that does not have any relationship from the other entity.

I use this block of codes to fetch the all the rows to this repository.

private translationTextRepository = getRepository(TranslationText);

async all(request: Request, response: Response, next: NextFunction) {
    return this.translationTextRepository.find();
}

And here's the entity for this repository.

@Entity('TranslationText')
export class TranslationText {

    @PrimaryGeneratedColumn()
    ID: number;

    @Column()
    CreatedBy: string;

    @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
    CreatedDate: Date;

    @Column()
    Status: boolean;

    @Column({ nullable: true, default: null })
    ModifiedBy: string;

    @Column({ type: 'timestamp', nullable: true, default: null })
    ModifiedDate: Date;

    @Column()
    Text: string;

    @ManyToOne((type) => Locale, (locale) => locale.ID)
    @JoinColumn({ name: 'LocaleID' })
    LocaleID: Locale;

    @ManyToOne((type) => TranslationTitle, (translationTitle) => translationTitle.ID)
    @JoinColumn({ name: 'TranslationTitleID' })
    TranslationTitleID: TranslationTitle;

}

But I was only able to fetch all the columns except the LocaleID and the TranslationTitleID.

How can I achieve this?

Upvotes: 15

Views: 10728

Answers (2)

Alexandre Vieira
Alexandre Vieira

Reputation: 283

Can you try to specify the relations like that:

async all(request: Request, response: Response, next: NextFunction) {
   return this.translationTextRepository.find({
     relations:["LocaleID","TranslationTitleID"]
    });
}

Because you have to make explicit that you want your relations on the query.

Upvotes: 6

charles
charles

Reputation: 438

Check this document: https://typeorm.io/#/relations-faq/how-to-use-relation-id-without-joining-relation solution:

  1. define new column:

    @column()
    LocaleID: number

rename old one to : Locale

But typeOrm cannot sync your table due to foreign key problem.

  1. use eager option in @ManyToOne({eager: true})

The search result will contain relation Locale object, you can take id from it.

Upvotes: 11

Related Questions