CakePHP 2.x Save 2 Level Deep hasMany associated data

In CakePHP 2.x we have hasMany, saveMany, saveAssociated model methods or functions to save associated data. These functions works great with straight associations but to make them work for multilevel associations you would need some tricks.

Following an example of two level deep hasMany assocation where:

UserCustomField hasMany UsersCustomFieldsList hasMany UsersCustomFieldsListEntry

In general to save the following hasMany and other association data

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

One would do:

However it would save the top level association data but not the second level hasMany data. The following would do the trick:

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

Leave a Reply

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