Hello. Faced a problem, how to specify when selecting a field in a query builder that are binding (in my case, many to many)?

User Entity

... /** * @ORM\ManyToMany(targetEntity="Role", inversedBy="users") * */ protected $roles; 

Role Essence

 ... /** * @ORM\ManyToMany(targetEntity="User", mappedBy="roles") */ private $users; 

The query is built in the User entity repository as follows:

 public function loadListOfUsers($fields = array('u')){ $query = $this ->createQueryBuilder('u') ->select($fields); $users = $query->getQuery()->getResult(); return $users; } 

In the controller:

  public function getAction() { $fields = array( 'u.id', 'u.username', 'u.email', 'u.avatar', 'u.isActive', 'u.roles', ); $restresult = $this->getDoctrine()->getRepository('AppUserBundle:User')->loadListOfUsers($fields); if ($restresult === null) { return new View("there are no users exist", Response::HTTP_NOT_FOUND); } return $restresult; } 

If you remove u.roles, everything is ok. But you need to get and roles, how can this be implemented?

  • it is not clear that there is such a field in the database at all? and what kind of error (Exception) do you have? - Naumov
  • There are 3 tables, users roles and users_roles which are connected as u.id = u_r.user_id and u_r.role_id = r.id. Those. Many-to-many links through the users_roles staging table. The roles field in the table is not present, it is a doctrine link, which contains an array of roles that belong to the user. The question is how to build a request to get these roles and specify only the necessary fields, if you ask everything, then a password comes along and a lot more that is not needed. Filter on the server side as it is not kosher IMHO. - LeshaZ

0