我想要实现一个结构,例如一个组织有许多部门,部门有很多人。
我已经设置了这样的模型结构:
组织
<?php
class Organisation extends AppModel {
public $hasMany = array(
'Department' => array(
'className' => 'Department',
'foreignKey' => 'organisations_id'
)
);
}
部门
<?php
class Department extends AppModel {
public $hasMany = array(
'Person' => array(
'className' => 'Person',
'foreignKey' => 'departments_id'
)
);
}
人
<?php
class Person extends AppModel {
}
然后我有一个像这样的控制器:
<?php
class OrganisationsController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
public function index() {
$this->set('organisations', $this->Organisation->find('all'));
}
}
当我打印出$组织时,我得到一个这样的数组:
Array
(
[0] => Array
(
[Organisation] => Array
(
[id] => 1
[created] => 2013-01-03 16:02:47
)
[Department] => Array
(
[0] => Array
(
[id] => 1
[created] => 2013-01-03 16:02:47
[organisations_id] => 1
)
)
)
)
我是PHP和CakePHP的新手,但是你不期望Person数组被包含在Organization数组中吗?如果没有,是否有其他方法可以实现如上所述的结构(组织 - >部门 - >人员)?
有关如何解决这个问题的任何提示都非常感谢! :)
答案 0 :(得分:3)
您可能正在寻找recursive
或者您可以使用containable behaviour
但请看一下结果。使用递归时,您可以获得许多您不想要的数据!所以请小心选择你真正需要的字段!
<强>递归强>
你会得到类似的东西:
<?php
class OrganisationsController extends AppController {
public $helpers = array('Html', 'Form', 'Session');
public $components = array('Session');
public function index() {
$this->Organisation->recursive = 2; # or -1, 0, 1, 2, 3
$this->set('organisations', $this->Organisation->find('all'));
}
}
您也可以在find中声明这样:
$this->set('organisations', $this->Organisation->find('all' array(
'recursive' => 2 # or -1, 0, 1, 2, 3
)
));
<强>中可容纳强>
class Organisation extends AppModel {
public $hasMany = array(
'Department' => array(
'className' => 'Department',
'foreignKey' => 'organisations_id'
)
);
$actsAs = array('Containable');
}
现在在您的控制器中,您可以执行以下操作:
$this->set('organisations', $this->Organisation->find('all', array(
'contain' => array('User')
)
));
但与往常一样,通往罗马的道路很多。所以请仔细阅读书籍!
答案 1 :(得分:1)