Typeorm find query doesn't return ManyToOne relation id

Viewed 4065

As the title says:

I have a business-user table and a business-hours table. buiness-hours has ManyToOne relationship with business-user.

The relationship on the side of business-hours is defined as below.

@ManyToOne(() => BusinessUser, (businessUser) => businessUser.businessHours)
@JoinColumn()
businessUser: BusinessUser;

Typeorm docs say that this should create a field as businessUserId in the table which it does. Also, as this is relationship on primary key then I don't need to name or refrence it. But when I do find orfindOne query, businessUserId is not returned anymore. When I check database, the field and vaulues are present as expected, just that they are not returned in find query. Earlier it was working fine and I was getting relation table id for all tables but now it doesn't work anymore. Wondering if anyone could help me this or figuring out what changed. I have already tried the solutions to the similar questions asked here, nothiing helped.

3 Answers

There is an "official" workaround on the official documentation. It explains "How to use relation id without joining relation".

To sum up, you just need to add a myRelationId (in your case, a businessUserId) column to your entity like this (for example):

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @Column({ nullable: true })
    profileId: number;  // <---------- You'll get only the id from here

    @OneToOne(type => Profile)
    @JoinColumn()
    profile: Profile;  // <----------- You don't want all the data

}

If you're doing it so, obviously, remove {relations : ["businessUser"]} from your requests.

before you save use cascades in one side of many to many relationship to save into both tables , when import user relations option and also businessUser is an array of BusinessUser

@ManyToOne(() => BusinessUser, (businessUser) => businessUser.businessHours ,{ cascade : true})
@JoinColumn()
businessUser: BusinessUser[];
const foundOne = await this.entity.findOne(id , {relations : ["businessUser"]})
const foundAll = await this.entity.findOne({relations : ["businessUser"]})

if you want to load it automatically use eager

@ManyToOne(() => BusinessUser, (businessUser) => businessUser.businessHours ,{ cascade : true , eager : true})
@JoinColumn()
businessUser: BusinessUser[];

you can try setting this loadRelationIds:true

for example I using something like this:

async findAByConditionWithRelationsOfUser(condition, relations, speaker_id) {  
     try {
          let data: SentenceEntity[] = await this.sentenceRespository.find({ where: condition, relations: relations, loadRelationIds:true });
          data = data.map(sentence => {
            for (let i = 0; i < sentence.sentenceToSpeaker.length; i++) {
              const element = sentence.sentenceToSpeaker[i];
              if (element.id == speaker_id) {
                sentence['recordedAudio'] = element
              };
            }
            delete sentence.sentenceToSpeaker;
            return sentence;
          })
          return data;
        } catch (error) {
          throw new HttpException(error, error.status)
        }
      }
Related