How to query a Many-to-Many relation with TypeORM

The SQL you are trying to get TypeORM to generate is roughly as follows

SELECT *
FROM subject
JOIN subject_note AS jt on jt.subject_id = subject.id
WHERE jt.note_id = :id

1. This is not possible with repo.find

At the time of writing, there is no way to create a where clause on a joined table using repo.find(...). You can join (doc) but the where clause only affects the entity of the repository.

TypeORM also silently ignores invalid where clauses, so be careful about those.

2. Re-select the note entity

If you want all the subject of a given note, you will either need to use a query builder, like you noted or you will need to re-select the note object with it’s relationships.

note = await noteRepo.find({
    relations: ['subjects'],
    where: { id: note.id }
});
const subjects = note.subjects

3. Use TypeORM lazy relations

If you want to avoid re-selection, you need to use TypeORM Lazy relations but this forces you to change the type in both entities to be a Promise

// note entity
@ManyToMany(() => Subject, (subject: Subject) => subject.notes)
subjects: Promise<Subject[]>;

// subject entity
@ManyToMany(() => Note, note => note.subjects)
@JoinTable()
notes: Promise<Note[]>;

With this lazy relations, you will need to await for the linked notes to load before each usage, but you will not need to provide an array of relations to the find method.

const note = await noteRepo.find({
    where: { id: someId }
});
const subjects = await note.subjects

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)