0

I am using Symfony Sonata User bundle for user management. I have created another entity as LoginHistory with OneToMany relationship between User and LoginHistory

I have to display the list of all users using KNP Paginator Bundle with their group name (normally belongs to one group only) with detail login history.

I have wrote this query, but it didn't get the group data of users.

 $query = $repository->createQueryBuilder('u')
                     ->join('PNCLogBundle:LoginHistory', 'log', 'WITH log.User = u.id')
                     ->innerJoin('u.groups', 'g')
                     ->andwhere('g.id = u.group')
                     ->where('u.roles LIKE :roles')
                     ->setParameter('roles', '%"ROLE_STAFF"%')
                     ->getQuery();
Wilt
  • 41,477
  • 12
  • 152
  • 203
Muhammad Taqi
  • 5,356
  • 7
  • 36
  • 61

1 Answers1

0

There are 2 types of JOINs: “Regular” Joins and “Fetch” Joins.

What you need is a fetch-join. You can read on this in the doctrine2 documentation. The solution is simple, just add g to your select clause in the query builder:

$query = $repository->createQueryBuilder('u')
                    ->select('u', 'g')
                    ->join('PNCLogBundle:LoginHistory', 'log', 'WITH log.User = u.id')
                    ->innerJoin('u.groups', 'g')
                    ->andwhere('g.id = u.group')
                    ->where('u.roles LIKE :roles')
                    ->setParameter('roles', '%"ROLE_STAFF"%')
                    ->getQuery();

You can also use the addSelect method:

$query = $repository->createQueryBuilder('u')
                    ->addSelect('g')
                    ->join('PNCLogBundle:LoginHistory', 'log', 'WITH log.User = u.id')
                    ->innerJoin('u.groups', 'g')
                    ->andwhere('g.id = u.group')
                    ->where('u.roles LIKE :roles')
                    ->setParameter('roles', '%"ROLE_STAFF"%')
                    ->getQuery();
Wilt
  • 41,477
  • 12
  • 152
  • 203
  • Got error that `Error: Expected Literal, got 'JOIN'` – Muhammad Taqi Jan 18 '16 at 09:27
  • This is not related to what I added in my answer, I think it is because of your join clause `->join('PNCLogBundle:LoginHistory', 'log', 'WITH log.User = u.id')`... [Check google you will find enough answers to solve that](https://www.google.com/webhp#q=Error%3A+Expected+Literal%2C+got+'JOIN'). You should probably do something like `->join('u.logs', 'log')` – Wilt Jan 18 '16 at 09:30