Request group object with the user

72 views Asked by At

I'm actualy learning Symfony and I'm making my own UserBundle for the reason that I have to use an online API to manage the users. So I joined the User and Group objects with doctrine ManyToOne relation. For the moment all is working properly.

Symfony is actualizing the User object on each page and getting the id of the group (cf. var_dump) but I want from Symfony to get the entire Group object on each page and not only the id of it.

User {#467 ▼
  -id: 104
  -uuid: "~"
  -username: "~"
  -lastLogin: null
  -websiteActivity: null
  -clientToken: "1c667ad4-07e2-4ffa-8db1-9997eadbbc4b"
  -accessToken: "b183f850ce4d4decb07cb7485c1d0a88"
  -dataCheck: DateTime {#457 ▼
    +"date": "2017-08-27 18:23:31.000000"
    +"timezone_type": 3
    +"timezone": "Europe/Berlin"
  }
  -reputation: 0
  -group: Group {#456 ▼
    +__isInitialized__: false
    -id: 4
    -inheritId: null
    -name: null
    -chatColor: null
    -websiteName: null
    -websiteColor: null
     …2
  }
}

If you know how to do that It would be really helpfull.

Thank you very much.

1

There are 1 answers

11
Jason Roman On BEST ANSWER

Keep in mind that $this->getUser() on a controller is an alias to the following:

$this->container->get('security.token_storage')->getToken()->getUser();

You can have a look at Using a Custom Query to Load the User. You could use that to automatically join to your Group entity:

public function loadUserByUsername($username)
{
    return $this->createQueryBuilder('u')
        ->select('u, g')
        ->leftJoin('u.group', 'g')
        ->where('u.username = :username OR u.email = :email')
        ->setParameter('username', $username)
        ->setParameter('email', $username)
        ->getQuery()
        ->getOneOrNullResult();
}

This was previously documented in Symfony versions <= 2.5 but was removed from the documentation for clarity and potentially because it wasn't needed for most cases. If you want you can also move this to your UserRepository (if it exists) and call it from there.

This would take effect when the user logs in. Try that to see if your Group object will be automatically retrieved.