cakephphas-and-belongs-to-manycakephp-2.6

Don't select an habtm field in a find


I am here trying to improve one of my select. My model is as follows:

Network
--->hasMany Esx
--->hasAndBelongToMany Environment

A network might have 0 Esx and/or 0 environments

So here I want to select some network information and the Esx section, but not the environment information.

  $this->Network->find('all',array(
          'conditions'=>array(
              'Network.plateform'=>IAAS,
              'Network.active'=>true),
          'fields'=>array(
              'Network.id',
              'Network.name')
     ));

So, I can't use fields to only select the vlan field
I can't lower recursive to remove environment because it would also remove Esx I found on SO an other question that suggest to use $this->Network->schema() and remove the unwanted fields, but it doesn't return the hm and habtm structure.

In short, how can I transform the result of this query from this

0 => array(
    'Network' => array(
          'id' => '38',
          'name' => 'HP_LOW'),
    'Esx' => array(...),
    'Environment' => array(...)
 )...

To this

 0 => array(
      'Network' => array(
        'id' => '38',
        'name' => 'HP_LOW'),
      'Esx' => array(...)
     )...

The purpose is not to just unset the Environment field, but to not select it in order to improve database perfomance.

Thank you! Ps: Im' workin with cakephp 2.6.2


Solution

  • use containable

    see the manual here

    in your Model you have to enable the Containable Behavior

    class Networkextends AppModel {
        public $actsAs = array('Containable');
    }
    

    then in the controller you can do

    $this->Network->find('all',array(
      'conditions'=>array(
          'Network.plateform'=>IAAS,
          'Network.active'=>true),
      'fields'=>array(
          'Network.id',
          'Network.name'),
      'contain'=>array(
          'Esx')
     ));