Saving multi-level associated data in CakePHP

In CakePHP 2 we had hasMany, saveMany, saveAssociated model methods or functions to save associated data. These functions works great with straight associations but to make them work for saving multi-level association data you need a trick.

 These functions works great with straight associations but to make them work for saving multi-level association data you need a trick

Following an example of two level deep hasMany assocation where:

UserCustomField hasMany UsersCustomFieldsList hasMany UsersCustomFieldsListEntry

In general for saving multi-level data following array structure should work:

[php]
array(
‘UsersCustomField’ => array(
‘field_name’ => ‘sdfsdfs’,
‘field_type’ => ‘dropdown’
),
‘UsersCustomFieldsList’ => array(
(int) 0 => array(
‘name’ => ‘sdfsfds’,
‘UsersCustomFieldsListEntry’ => array(
(int) 0 => array(
‘name’ => ‘sdfsdfs’
),
(int) 1 => array(
‘name’ => ‘sdfsdfsd’
)
)
)
)
)
[/php]

and to save it, one would do:

[php]$this->UsersCustomField->saveAll($data);[/php]

It works, but it saves only the top level association data but not the second level association data. The following would do the trick for saving 2-level associated data in CakePHP 1&2:

[php]$options[‘deep’] = true;
if ($this->UsersCustomField->saveAll($this->request->data, $options))[/php]

In CakePHP 3 however it has little bit different syntax for saving multi-level associations. Once has to specify
'associated'
in the options while saving an entity. For example:

[php]$user = $this->Users->patchEntity($user, $this->request->data, [
‘associated’ => [‘Employees’, ‘Employees.Courses’]
]);[/php]

Leave a Reply