我试图弄清楚如何在CakePHP 3.x中获取嵌套子对象的值
一个基本的例子包括三个实体:
服务器,机架,Operating_System
表:
机架 - id,名称
服务器 - id,hostname,rack_id,operating_system_id
Operating_systems - id,name
Rack hasMany Servers
服务器所属于操作系统和属于机架
如何在Rack View中引用Rack-> Server-> OperatingSystem-> name?
//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']); }不确定这是否最终成为控制器中的自定义查询,或者是否有内置的Cake语法来完成我需要的内容。 谢谢你的帮助。
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.
最满意答案
尝试:
$rack = $this->Racks->get($id, [ 'contain' => ['Servers' => 'OperatingSystems'] ]);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.
更多推荐
发布评论