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:

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

and to save it, one would do:

$this->UsersCustomField->saveAll($data);

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:

$options['deep'] = true;
if ($this->UsersCustomField->saveAll($this->request->data, $options))

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:

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

Leave a Reply

Your email address will not be published. Required fields are marked *