Search code examples
ormnestjstypeorm

createQueryBuilder with getOne doesn't return @JoinColumns inside table Typeorm


I have a project written by nestjs and typeorm. In my project I have tables chat and user so I want to get ManyToOne relationships. Here is the chat table

export class Chat extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;

@ManyToOne(() => User, (user) => user.chatsCreater, { nullable: false })
@JoinColumn({ name: 'creatorId' })
creator: User;

@ManyToOne(() => User, (user) => user.chatsCompanion, { nullable: false })
@JoinColumn({ name: 'companionId' })
companion: User;
}

and chunk from user table

...   
@OneToMany(() => Chat, (chat) => chat.creator)
chatsCreater: Chat[];

@OneToMany(() => Chat, (chat) => chat.companion)
chatsCompanion: Chat[];
...

When I query data from chat I expect to get the hole table {id, companionId, creatorI} not only value of chat.id. Here is my query

.createQueryBuilder('chat')
.where('chat.creatorId = :creatorId AND chat.companionId = :companionId', { creatorId, companionId })
.getOne()

and the result {id: 1} So what I want is to get values of companionId and creatorId too when I query from chat. If I change getOne() to getRaw() I get the desired output. But in case of more complex queries (with multiple joins) it becomes a mess with getRaw so is there a way to get all columns using getOne ?


Solution

  • I was able to do it by using leftJoinAndSelect

    .createQueryBuilder('chat')
      .leftJoinAndSelect('chat.creator', 'creator')
      .leftJoinAndSelect('chat.companion', 'companion')
      .where('chat.creatorId = :creatorId AND chat.companionId = :companionId', { creatorId, companionId })
      .getOne();
    

    In case if hole table is not needed it's also possible to use leftJoin without select and later add to query addSelect(['creator.id','companion.id'])