P
P
postgresdev2019-06-11 20:46:29
symfony
postgresdev, 2019-06-11 20:46:29

Is it correct to specify foreach in a repository in Symfony?

It is necessary to make a selection of one column in the form of an array. Which is more correct: foreach in a service or a repository?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Flying, 2019-06-12
@postgresdev

You should take a look at the different hydrator modes in Doctrine. In particular, in your case, you will most likely want to use scalar hydration on the results of a single column sample. With this mode, array_column() works very well , so your method could look something like this (in the example, the column is fetched emailfrom entity User):

public function getEmails()
{
    return array_column($this->getEntityManager()
        ->createQuery('select u.email from User u')
        ->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR), 'u_email');
}

or, if you, for example, need a relationship between id and email:
public function getEmails()
{
    return array_column($this->getEntityManager()
        ->createQuery('select u.id, u.email from User u')
        ->getResult(\Doctrine\ORM\Query::HYDRATE_SCALAR), 'u_email', 'u_id');
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question