I’ve 3 tables.
- Device hasOne DeviceGroup
- Group hasMany Devices
- DeviceGroup (belongs to Device and Group)
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?
There are a few ways to achieve this.
It may be as simple as:
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:
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.phpso that all Models are automatically Containable enabled):And then without having to add Group to the Device Model you can do this:
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 yourfindyou’ll be zipping along.