I have the following array and I want to group all the users of same company together. Currently every user is shows up with a company id and some times there are 2 or more users under one compay. So I kinda want to revert it and show the users under company not company under users. How’d I go about doing that
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] =>
)
)
)
)
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:
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:
Then in the find() call:
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:
Try both approaches and see what you come up with.