多层次的“有很多”关系

时间:2013-01-04 09:22:31

标签: php cakephp

我想要实现一个结构,例如一个组织有许多部门,部门有很多人。

我已经设置了这样的模型结构:

组织

<?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数组中吗?如果没有,是否有其他方法可以实现如上所述的结构(组织 - >部门 - >人员)?

有关如何解决这个问题的任何提示都非常感谢! :)

2 个答案:

答案 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)

Recursive函数将为您完成。

只需在OrganisationsController索引函数中,尝试如下所示。

  $this->Organisation->recursive = 2;
  $this->set('organisations', $this->Organisation->find('all'));

注意:递归可能会影响您的效果,您可以使用unbind方法通过获取所需数据来摆脱它。

相关问题