Reputation: 31
I'm struggling with queries over many-to-many relation using typeorm. I have two entities: users and groups, both having many-to-many relations to each other. User entity has this:
@ManyToMany(() => Group, group => group.users)
@JoinTable()
groups: Group[];
Group entity has this:
@ManyToMany(() => User, user => user.groups)
users: User[];
I want to get all groups of a specified user, that have a certain value. In my case, I want all groups for user X that have ishidden = false
. So I tried diffentent things, but none work...
const groups = this.groupRepository.find({
relations: ['users'],
where: {
ishidden: false,
users: {
id: user.id
}
}
});
I was really hoping that it would work this way, but it just throws Cannot query across many-to-many for property users
. Other approaches with querybuilder also didnt work :-(
I can't be that hard the query a related table, can it? I'm coming from the C# world, so maybe I'm just doing it wrong ;-)
Upvotes: 3
Views: 9599
Reputation: 31
Recently faced a similar problem(nestjs + ts + typeorm). Try something like this:
import { Connection } from 'typeorm';
// some code
constructor(private connection: Connection) {}
// some code
await this.connection
.getRepository(Group) // group entity
.createQueryBuilder('groups') // table name
.leftJoin('groups.users', 'users') // join group table and user table
.where('ishidden = false AND users.id = :userId ', {
userId: userId,
})
.getMany();
Upvotes: 3