Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 747
Rich Avatar asked Jul 11 '19 06:07

Rich


Video Answer


2 Answers

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.

like image 134
charles Avatar answered Oct 02 '22 19:10

charles


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.

like image 31
Alexandre Vieira Avatar answered Oct 02 '22 17:10

Alexandre Vieira