i have 2 entities with ManyToMany relation:
//branch entity
@ManyToMany(
(type) => User,
(e) => e.branches
)
users: User[];
//user entity
@ManyToMany(
(type) => Branch,
(e) => e.users,
{ eager: true,
cascade: false }
)
@JoinTable()
branches: Branch[];
@IsEnum(Role)
@Column('text', { default: Role.Client })
role: Role;
I want to find branches if users list not contain user with role 'client'.
i need this, if i have:
[
Branch {
id: '98007770-c924-43cd-988c-774492e1e759',
name: 'poslovnica1',
users: [ {role:'client'},{role:'superAdmin'} ]
},
Branch {
id: '787007770-c924-43cd-988c-774492e1e759',
name: 'poslovnica13',
users: [ {role:'client'},{role:'superAdmin'} ]
},
Branch {
id: '36f5b1ad-6553-4b2f-936b-33fb4ca8e73e',
name: 'poslovnica2',
users: [ {role:'superAdmin' }]
}
]
after filter i want to get, all branches if they not have user with role 'client'. 'superAdmin' or:
[
Branch {
id: '36f5b1ad-6553-4b2f-936b-33fb4ca8e73e',
name: 'poslovnica2',
users: [ {role:'superAdmin'} ]
}
]
Welcome to StackOverflow !
You were close to it indeed !
I'd give it a try with the following piece of code (using lodash):
import {values, omit} from 'lodash';
// ....
const notClientRoles = values(omit(Role, Role.Client));
await this.branchRepository
.createQueryBuilder('b')
.leftJoin('b.users', 'users')
.where('users.client IN(:...roles)', { roles: notClientRoles })
.getMany();
Details:
const notClientRoles = values(omit(Role, Role.Client))
is used to remove the Client
role from the ones you want (we use values
and omit
methods from lodash
). We wrap it in a variable and then use it in our where
clause, like this:
.where('users.client IN(:...roles)', { roles: notClientRoles })
Let me know if it helps:)
i get same result like you try with lodash, but in another way:
await branchRepository.find({
join: {
alias: 'branch',
leftJoinAndSelect: {
users: 'branch.users'
}
},
where: (qb) => {
qb.where('role != :role', { role: 'client' });
}
});
but i need to filter branches by users, not users... Thanks for try!
i get what i want:
retVal = await this.branchRepository.find({ relations: ['users'] });
retVal = retVal.filter((branch: Branch) => {
if (!branch.users.some((user) => user.role === Role.Client)) return branch;
});
but i looking to improve this if is posible...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.