0

An user has one role. A role has zero or many users.

I would like to find roles without users.

I need to have this query without using IN or NOT IN

I tried with join:

$qb = $this->createQueryBuilder('role');
$qb
    ->leftJoin('role.users', 'users')
    ->where('users IS NULL')

without join

$qb = $this->createQueryBuilder('role');
$qb
    ->where('role.users IS NULL')

with id:

$qb = $this->createQueryBuilder('role');
$qb
    ->leftJoin('role.users', 'users')
    ->where('users.role != role')

Do you have other ideas? Do I have no other choices than to use IN / NOT IN queries?

Thanks in advance

M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
goto
  • 7,908
  • 10
  • 48
  • 58

1 Answers1

2

You can find roles that don't have any users by using a count query

$qb = $this->createQueryBuilder('role');
$qb ->addSelect('COUNT(users.id) AS total_users')
    ->leftJoin('role.users', 'users')
    ->groupBy('role.id')
    ->having('total_users = 0')
    ->getQuery()->getResult();
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118