Select specific columns from a repository in Doctrine 2

1

First, we know that depending on the number of columns in a query, you can increase response time.

In Doctrine I call the following repository, which has a relationship and which brings all the columns of both entities.

public function index()
{
    $this->alunos = $this->model->getRepository()->findAll();
}

But thinking about the statement I gave earlier, does the return of this repository take longer than if it were an entity without a relationship?

And another question?

Can I select the columns I want to return from this repository? For example, the above repository returns:

id (entidade aluno)
nome (entidade aluno)
id_turma (entidade turma)

But I would like it to return only the student's name.Type like this:

public function index()
{
    $this->alunos = $this->model->getRepository()->findAll("nome");
    // ou assim pra pegar mais de um campo
    $this->alunos2 = $this->model->getRepository()->findAll("nome, dtNascimento");
}

I know it does not work like that, just to give an example.

    
asked by anonymous 31.12.2014 / 18:25

2 answers

1

Starting with the second question, you have the possibility to use query builders

$query = $em->createQuery('SELECT u.id FROM CmsUser u');
$ids = $query->getResult(); // array of CmsUser ids

see here: link

The first question: In relation to this I think performance may vary. If I'm not mistaken, Doctrine treats everything as objects and when you load a certain entity all its dependencies are loaded.

Doctrine leaves the slower application by using resources. You will have to see what is most feasible for you. Use profile tools to measure the resources you use. I think in ZendF and Symfony you have components that measure it.

    
31.12.2014 / 22:52
1

What you can do is to have you return a custom repository to a specific model , instead of returning the default Doctrine% .

In this custom repository, which inherits the EntityReposity class, you overwrite the functions so that they return only the columns you want.

Class EntityRepository :

<?php

namespace MyDomain\Model;

use Doctrine\ORM\EntityRepository;

/**
 * @Entity(repositoryClass="MyDomain\Model\AlunoRepository")
 */
class Aluno
{
}

Class MyDomain\Model\Aluno :

<?php

namespace MyDomain\Model;

class AlunoRepository extends EntityRepository
{
    public function findAll()
    {
        return $this->_em
            ->createQuery('
                SELECT a.coluna1, a.coluna2, a.coluna3
                FROM MyDomain\Model\Aluno a')
            ->getResult();
    }
}
    
01.01.2015 / 22:33