F
F
fman22018-11-03 22:15:51
symfony
fman2, 2018-11-03 22:15:51

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' => [...]
]

I can easily make such an array by hand by getting the data through QueryBuilder. I can serialize an object. But is there such an opportunity to do this automatically and not form an array by hand and not incur costs during serialization? What is the correct way in Symfony to do this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2018-11-04
@Minifets

What is the correct way in Symfony to do this?

The correct way is to use the serializer.
I don't know why you have such doubts about the performance of this tool. Because it even has caching when dealing with doctrine entities.
If just out of curiosity, then the layer can really be removed.
Thus
/**
 * Примерная реализация метода получения билета по 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);
}

O
OnYourLips, 2018-11-03
@OnYourLips

You can make it a serializer. It is not necessary to form by hand.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question