Answer the question
In order to leave comments, you need to log in
What is the correct way to return an array from a Repository in Symfony 4.1?
Hello. I am writing a "training" project on Symfony 4.1
Question:
There is an Entity with all connections (App\Entity\Ticket), where there is getUser(), getAnswers() and so on.
There is a repository that returns a Ticket for a certain ID.
There is a Vue frontend that this ticket renders. As you understand, all communication with the client is based on JSON.
I can convert an object to an array through symfony/serializer, but how can I remove this layer?
I don't need this extra overhead, I just want to write: $repository->findAsArray($id);
and get an array with all the links:
$ticket = [
'id' => 100,
'name' => 'ticket',
'user' => [...],
'answers' => [...]
]
Answer the question
In order to leave comments, you need to log in
What is the correct way in Symfony to do this?
/**
* Примерная реализация метода получения билета по id
*
* @param int $id
* @return array|null
* @throws \Doctrine\ORM\NonUniqueResultException
*/
public function findAsArray(int $id): ?array
{
return $this->createQueryBuilder('t')
->select('t, u, a')
->join('t.user', 'u')
->join('t.answers', 'a')
->andWhere('t.id = :id')
->setParameter('id', $id)
->getQuery()
->getOneOrNullResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
}
You can make it a serializer. It is not necessary to form by hand.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question