I'm using FOSUserBundle and FOSRestBunldle with Symfony 2.8 and have to get a short user List with age, however there is no field 'age' in the user database, which is why my User entity class has this custom getter to calculate the age from the birthdate field
public function getAge()
{
$now = new \DateTime('now');
$age = $this->birthdate->diff($now);
return $age->format('%y');
}
Getting my user list with "u.age" and serializing it to json however, does not work, as there is no real field associated with u.age
$query = $em->createQuery('SELECT u.username, u.age FROM AppBundle:User u');
$users = $query->getResult();
Using the Repository with ->findAll()
would get the ages, but also loads a lot of other related entities (posts, comments by the user) which are not needed here and would be a bit of an overload.
How can i get a list of my users with just their username and respecive age?
thank you for your help!
You don't have age
field in DB, which also means you don't have it in Doctrine mapping, therefore you can't select it. Doctrine doesn't know anything about it.
You need to select data that is required to calculate it inside entity instance. In this case in order to calculate user's age you probably want to select birthday date.
E.g.:
$query = $em->createQuery('SELECT u.username, u.birthday FROM AppBundle:User u');
$users = $query->getResult();
Then you should be able to get age from your entity in PHP code.