vibha
vibha

Reputation: 129

Cakephp relationship in three tables

I've 3 tables.

Now if I do $this->Device->find('all'); it gives me result:

Device => array
DeviceGroup => array

Now I want values from Group table as well, how can I do that?

Upvotes: 0

Views: 828

Answers (1)

ianmjones
ianmjones

Reputation: 3415

There are a few ways to achieve this.

It may be as simple as:

$this->Device->find('all', array('recursive' => 2));

But that can be pretty resource heavy and wasteful if you have other models that will get automatically retrieved.

Another way would be to add the Group class to your Device model:

var $hasOne = array(
  'DeviceGroup' => array(
    'className' => 'DeviceGroup',
    'foreignKey' => 'device_group_id',
    'dependent' => false,
    'conditions' => '',
    'fields' => '',
    'order' => ''
  ),
  'Group' => array(
    'className' => 'Group',
    'foreignKey' => false,
    'dependent' => false,
    'conditions' => 'Group.id = DeviceGroup.group_id',
    'fields' => '',
    'order' => ''
  )
);

This can be problematic when you then try and do a find from another model that automatically includes Device's Group relationship when you already have Group in the find. So best to name it something else in the $hasOne, such as 'DeviceGroupGroup', which is painful.

My prefered method would be to enable the Containable behaviour (I do this in app/app_model.php so that all Models are automatically Containable enabled):

class AppModel extends Model {
  var $actsAs = array('Containable');
}

And then without having to add Group to the Device Model you can do this:

$this->Device->find(
  'all',
  array(
    'contain' => array('DeviceGroup', 'Group'),
    'recursive' => 2,
  )
);

This way, even though you are recursing relatively deeply, you are only retrieving the models that you actually want, and if you also use the 'fields' parameter on your find you'll be zipping along.

Upvotes: 1

Related Questions