In plain-vanilla model, Cake's model linkage is determined by your models' recursive
attribute. Your example model relationship looks something like this:
User
-> belongsTo Company
-> hasMany Department
-> hasMany Address
-> hasMany PhoneExtension
(I've added an additional relationship (User hasMany PhoneExtension
) to flesh out the following explanation.)
There are three accepted values for Model::recursive
: -1, 0, 1 and 2. Each value indicates to Cake's ORM a different depth to retrieve model records. I'll use $this->User->find('all')
to illustrate the difference.
At recursive = -1
, Cake retrieves only the specified model (ie. User
). It parses none of the model associations.
At recursive = 0
, Cake retrieves the specified model, and parses its belongsTo
associations. $this->User->find('all')
would retrieve all User
records, as well as the Company
record to which each User
belongs.
At recursive = 1
, Cake retrieves the specified model, and parses all of its direct associations. $this->User->find('all')
would retrieve all User
records, as well as the Company
record to which each User
belongs, and all PhoneExtension
records belonging to the User
.
At recursive = 2
, Cake retrieves the specified model, parses all of its direct associations and all associations of its direct associations. $this->User->find('all')
would retrieve everything in the example model relationship diagram: all User
records, the Company
records to which the User
records belong, all PhoneExtension
records belonging to the User
, and all Department
and Address
records belonging to the Company
.
Which is the very long way of saying that yes, you can achieve the results you indicate in your question, at recursive = 2
.
If you wanted to go deeper than what recursive = 2
gets you, you'll have to use the Containable
behaviour. Let's say that your Department
model had an additional association: hasMany Group
. Thus:
User
-> belongsTo Company
-> hasMany Department
-> hasMany Group
-> hasMany Address
-> hasMany PhoneExtension
To retrieve everything we got with a recursive = 2
retrieval, as well as all the associated Group
records, you'd construct your Model::find
call like this:
$this->User->find('all', array(
'contain' => array(
'PhoneExtension',
'Company' => array(
'Department' => array( 'Group' ),
'Address'
)
)
));