1

I am trying to use TypeORM to build highly relational data and make highly relational data queries. My current goal is to select all "leads" from the members table where the committee they are a lead of corresponds to a given committee id.

I have tried and failed to use repository.find() to do this. You can see in my code below.

   public async getLeadsFromCommittee(committeeId: number): Promise<Member[]> {
        const results = await this.memberRepository
            .createQueryBuilder()
            .select("member")
            .from(Member, "member")
            .innerJoinAndSelect("member.leadOf", "member")
            .getMany();
        return results;
        // return await this.memberRepository.find({ // my failure!
        //     where: { // but IMO this ... should work
        //         leadOf: {
        //             committeeId,
        //         },
        //     },
        // });
    }

find({}) failed me. Perhaps I was using it wrong. But TypeORM's docs suggest that the createQueryBuilder is more powerful, so I'm trying that. But I'm new to using it, hence all I have to go on is one example in the docs which I've failed to utilize.

This post says that what I want is to INNER JOIN: "returns rows when there is a match in both tables."

Here is my (super duper interrelated) Members entity definition:

@Entity()
export class Member {
    @PrimaryGeneratedColumn()
    memberId: number;

    @ManyToMany(() => Committee, committee => committee.leads, { nullable: true, onDelete: "CASCADE" })
    @JoinTable({ name: "lead_of" })
    leadOf?: Committee[];
}

And here is the Committees entity definition:

@Entity()
export class Committee {
    @PrimaryGeneratedColumn({ name: "committee_id" })
    committeeId: number;

    @ManyToMany(() => Member, member => member.memberId, { eager: true, nullable: true, onDelete: "CASCADE" })
    @JoinTable({ name: "leads_for_committee" }) 
    leads?: Member[];
}

Lots of entries in the two entity definitions are deleted for brevity, but probably irrelevant.

plutownium
  • 1,220
  • 2
  • 9
  • 23

0 Answers0