How to remove table of results from a Cakephp find()?

Asked

Viewed 388 times

2

I have 3 related tables: Usuario, Movimentacao and Grupo

I’m using:

$usuarios = $this->Usuario->find('all',array(
    'recursive' => 1,
    'fields' => "Usuario.id, Usuario.nome, Usuario.email"
    'order' => array('Usuario.nome ASC')
));

However, the recursive => 1 is bringing the three tables. If placed 0, returns only User. I need to return only User and Group, because, bringing Movement, the query is too slow. How do I eliminate Movement query?

2 answers

1


You can temporarily disassociate the other model:

$this->Usuario->unbindModel(array('hasAndBelongsToMany' => array('Movimentacao')));

(Substitute hasAndBelongsToMany by the kind of relationship you’re using.)

0

In giving unbind, you fully remove the relationship of this model during execution.

I recommend selecting data in 2 ways:

For direct associations, you can pass recursive together with Fields and thus limit the returned data. For example:

$result = $this->Usuario->find('all', array(
    'conditions' => array('Usuario.status' => 'ativo'),
    'recursive' => 1,
    'fields' => array('Usuario.nome', 'Grupo.nome')
));

For deep associations use Containable Behavior (http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html)

Example of use in a controller:

$this->Usuario->Behaviors->load('Containable');
$result = $this->Usuario->find('all', array(
    'conditions' => array('Usuario.status' => 'ativo'),
    'contain' => array('Grupo')
));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.