0

我有以下数组,我想将同一家公司的所有用户分组在一起。目前,每个用户都会显示一个公司 ID,有时一个公司下有 2 个或更多用户。所以我有点想恢复它并显示公司下的用户而不是用户下的公司。我是怎么做到的

Array
(
    [0] => Array
        (
            [User] => Array
                (
                    [id] => 1
                    [company_id] => 20
                    [type] => 
                )


        )

    [1] => Array
        (
            [User] => Array
                (
                    [id] => 6
                    [company_id] => 21
                    [type] => 
                )


        )

    [2] => Array
        (
            [User] => Array
                (
                    [id] => 7
                    [company_id] => 22
                    [type] => 
                )


        )

    [3] => Array
        (
            [User] => Array
                (
                    [id] => 14
                    [company_id] => 21
                    [type] => 
                )


        )

    [4] => Array
        (
            [User] => Array
                (
                    [id] => 15
                    [company_id] => 22
                    [type] => 
                )



        )

    [5] => Array
        (
            [User] => Array
                (
                    [id] => 16
                    [company_id] => 21
                    [type] => 
                )


                )

        )

)
4

2 回答 2

1

From the example I suppose that your relations are as follows:

"User belongsTo Company" and "Company hasMany User"

@tigrang is right, if you do a find on Company, you will get the users Grouped by Company:

$this->Company->find('all', array('conditions' => array('id' => $companyId)));

If your Company Model has many other relations and you need only the Users you can use the ContainableBehaviour. Firstly add it in the Company model:

public $actsAs = array('Containable);

Then in the find() call:

$this->Company->find('all', array('conditions' => array('id' => $companyId), 'contain' => array('User')));

The 'contain' key accepts an array of Model names or a string for a single Model. It will adjust the model bindings on the fly, leaving you only with the Company and User models' data (if used as in the example above).

And a little thing I missed. You can also use the 'group' key in a find over the User model:

$this->User->find('all', array('group' => 'company_id'));

Try both approaches and see what you come up with.

于 2012-05-11T09:53:20.737 回答
-1

使用递归或 ContainableBehavior 在 Company 模型上进行查找。

于 2012-05-10T18:42:51.123 回答