I have 2 entities User and Post linked with a One-To-Many relationship.
I am writting a query with the queryBuilder to extract needed user details and some info about the posts of the given user :
return $this->createQueryBuilder('u')
->select('u.id AS userId, u.username, u.email, u.createdAt, u.roles ')
->leftjoin('u.posts', 'p')
->select('p.description, p.postPic')
->andWhere('u.id = :id')
->setParameter('id', $id)
->getQuery()
->getResult()
;
The result is obviously something like that:
[
{
"userId": 1,
"username": "Toto",
"email": "[email protected]",
"createdAt": "2024-02-22T16:13:06+01:00",
"roles": [],
"description": "super Post from Toto",
"postPic": "https://images.pexels.com/photos/8159657/pexels-photo-8159657.jpeg"
},
{
"userId": 1,
"username": "Toto",
"email": "[email protected]",
"createdAt": "2024-02-22T16:13:06+01:00",
"roles": [],
"description": "another Super Post from Toto",
"postPic": "https://images.pexels.com/photos/8159657/pexels-photo-8159657.jpeg"
}
]
but what I would like to reach is:
[
{
"userId": 1,
"username": "Toto",
"email": "[email protected]",
"createdAt": "2024-02-22T16:13:06+01:00",
"roles": [],
"posts": [
{
"description": "super Post from Toto",
"postPic": "https://images.pexels.com/photos/8159656/pexels-photo-8159656.jpeg"
},
{
"description": "another Super Post from Toto",
"postPic": "https://images.pexels.com/photos/8159657/pexels-photo-8159657.jpeg"
},
]
}
]
I am searching a way to show a Collection property like it is when there is no select with createQueryBruilder() but with a select to be able to choose which field to get from the entity.
Does anyone have a suggestion on the best way to do it please?