Being a CakePHP newbie I found it hard to find any information on this topic, and the answer is in fact really really simple.
The answer
$project = $this->Projects->get($id, [ 'contain' => [ 'Customers', 'Estimates' => [ 'Types', 'Projects' ], 'Logs' => [ 'Types', 'Projects' ], 'Statuses' ] ]);
The question
I have a couple of models related to each others; Customers, Projects, Logs, Estimates, Types and Statuses.
Each customer has serveral Projects.
Each Project has serveral Logs and Estimates and a Status.
A Log and an Estimate has a Type.
I ran complete out-of-the-box scaffolded CakePHP app, and all worked fine. In the single project view I also saw related Logs, but the Type field for each Log showed an integer – the type_id. I wanted instead to show the Type name, but found it really hard to find how.
This is where the answer above comes in handy. The documentation for CakePHP 3.0 mentions how to add table names to the contain-parameter, but I haven’t found any mention of it being possible to nest multiple tables inside the parameter.
Take the following example:
$project = $this->Projects->get($id, [ 'contain' => [ 'Customers', 'Estimates' => [ 'Types', 'Projects' ], 'Logs' => [ 'Types', 'Projects' ], 'Statuses' ] ]);
Here I’m in my ProjectsController’s view function. By default it contains all tables directly related to the current project (Customers, Estimates, Logs, Statuses). In my view I can use $project->customer->name to get the name of the customer assigned to the project. Likewise I can use $estimates->description inside a foreach( $project->estimates), but I cannot use $estimates->type->name, since the Types table is not directly related to the Projects table.
Thus; Nesting the contains parameter. This lets me join the Types table to the Estimates table – which lets me get the $estimates->type->name object.
Simple as that, but obviously really hard to find out (or I simply just suck at Googling).
Some of the google queries I tried before finding this out were:
cakephp show related field
cakephp get joined fileld
cakephp include related model