0
votes

I'm trying to figure out how it's possible to get the value of a nested child object in CakePHP 3.x

A basic example consists of three entities:

Server, Rack, Operating_System

Tables:

Racks - id, name

Servers - id, hostname, rack_id, operating_system_id

Operating_systems - id, name

Rack hasMany Servers

Server belongsTo OperatingSystems & belongsTo Racks

How can I reference Rack->Server->OperatingSystem->name in my Rack View?

//View.ctp
<?php foreach ($rack->servers as $servers):
echo h($servers->hostname) 
echo h($servers->operating_system->name)   //Doesn't output OS Name
endforeach; ?>

//View Function in RacksController:
public function view($id = null)
{
    $rack = $this->Racks->get($id, [
        'contain' => ['Servers']
    ]);
    $this->set('rack', $rack);
    $this->set('_serialize', ['rack']);
}

Not sure if this ends up being a custom query in the controller or if there is a built-in Cake syntax to accomplish what I need. Thanks for any help.

2

2 Answers

1
votes

Found the answer:

Cake 3.x passing-conditions-to-contain

$rack = $this->Racks->get($id, [
        'contain' => ['Servers','Servers.OperatingSystems']
    ]);

Solution is to use the dot notation for deeply nested associations. Thanks to aknd for pointing me in the right direction.

0
votes

try:

$rack = $this->Racks->get($id, [
    'contain' => ['Servers' => 'OperatingSystems']
]);