Filtering many to many relationship in typeorm

Viewed 1338

So I have two entities Target and Contact having a many to many relationship. How can I filter Contact based on a particular target in typeorm.

export class Contact {
@PrimaryGeneratedColumn()
id: number;

@Column()
name: string;

@Column()
contactno: string;

@Column()
email: string;

@ManyToMany(
    () => Target,
    target => target.contacts
)
@JoinTable()
targets: Target[];
}

export class Target {

@PrimaryGeneratedColumn()
id: number;

@Column()
name: string;

@ManyToMany(
    () => Contact,
    contact => contact.targets,
    { cascade: true }
)

}

Now I'm fetching using the following queryBuilder

this.contactRepository
        .createQueryBuilder("contact")
        .select(["contact"])
        .leftJoinAndSelect("contact.targets", "target")
        .where("contact.targets= :targets", {targets: "4"})
        .getMany();

But this is producing a

QueryFailedError: column contact.contactId does not exist
at new QueryFailedError (/home/niel_99/Internship/wf/src/api/node_modules/typeorm/error/QueryFailedError.js:11:28)
at Query.callback (/home/niel_99/Internship/wf/src/api/node_modules/typeorm/driver/postgres/PostgresQueryRunner.js:176:38)
at Query.handleError (/home/niel_99/Internship/wf/src/api/node_modules/pg/lib/query.js:146:19)
at Connection.connectedErrorMessageHandler (/home/niel_99/Internship/wf/src/api/node_modules/pg/lib/client.js:233:17)
at Connection.emit (events.js:310:20)
at /home/niel_99/Internship/wf/src/api/node_modules/pg/lib/connection.js:109:10
at Parser.parse (/home/niel_99/Internship/wf/src/api/node_modules/pg-protocol/dist/parser.js:42:17)
at Socket.<anonymous> (/home/niel_99/Internship/wf/src/api/node_modules/pg-protocol/dist/index.js:8:42)
at Socket.emit (events.js:310:20)
at addChunk (_stream_readable.js:286:12)
at readableAddChunk (_stream_readable.js:268:9)
at Socket.Readable.push (_stream_readable.js:209:10)
at TCP.onStreamRead (internal/stream_base_commons.js:186:23)

I have a contact table, target table and contact_targets_target table in my db, where the contact_targets_target is storing contactId against targetId

1 Answers

in my case i didn't used querybuilder, but you can try .find or .findandcount exemple :

let res = await this.userRepository.findAndCount({
      relations: ["roles", "company"],//this for the relation many-to-many
      where: `(username like '%${seachValue}%' or firstname like '%${seachValue}%' 
      or lastname like '%${seachValue}%' or email like '%${seachValue}%')`,
      order: {
        username: sortDirection,
      },
      skip: pageNumber * listeNumber,
      take: listeNumber,

    });
Related