3

たとえば、組織に多くの部門があり、部門に多くの人がいるような構造を実現したいと思います。

モデル構造を次のように設定しました。

組織

<?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'));
    }

}

$ Organizationsを印刷すると、次のような配列が得られます。

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配列に含まれることを期待しませんか?そうでない場合は、上記のような構造を実現する別の方法がありますか([組織]->[部門]->[個人])?

これについてのヒントは大歓迎です!:)

4

2 に答える 2

3

あなたはおそらく再帰を探しています

または、封じ込め可能な動作を利用することもできます

しかし、結果を見てください。再帰を使用すると、不要なデータを大量に取得できます。したがって、注意して、実際に必要なフィールドを選択してください。

再帰的

次のようなものが得られます:

<?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'));
    }
}

次のように、検索自体でこれを宣言することもできます。

$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')
    )
));

しかし、いつものように、ローマに通じる道はたくさんあります。ですから、本を注意深く読んでください!

于 2013-01-04T09:31:08.550 に答える
1

再帰関数がそれを行います。

OrganisationsControllerインデックス関数で、以下のようにしてみてください。

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

注:再帰はパフォーマンスに影響を与える可能性があります。必要なデータをフェッチするだけで、 unbindメソッドを使用してそれを取り除くことができます。

于 2013-01-04T09:30:17.893 に答える