cakephp - has many through not saving
cakephp
Solution
In order to save a `hasMany` relationship with `saveAll`, the `hasMany`-associated model data (in this case, `$d['AlertsElement']`) needs to be an indexed array of associative arrays, thus:
$d = array(
'Alert' => array(
'id' => 1976
),
'AlertsElements' => array(
0 => array(
'ordering' => 2
)
)
);
$this->Alert->saveAll($d);
Note that the associative array, consisting of the `'ordering'` key and its value, has been shifted down into an indexed array. This is the required format for saving `hasMany`-associated data in a single `saveAll` operation, because this format expands gracefully whether you want to save one or ten associated records.
Refer to the Cake manual on saving related model data for more info.
Problem
I have the following has many through relationship ``` Alert AlertsElement Search id id id name alert_id link search_id ordering ``` Here are my models ``` class Alert extends AppModel { var $name = 'Alert'; var $hasMany = array('AlertsElement'); class AlertsElement extends AppModel { var $name = 'AlertsElement'; var $belongsTo = array('Alert','Search'); class Search extends AppModel { var $name = 'Search'; var $hasMany = array('AlertsElement'); ``` Here is my test code I am using to do a save - ``` $d = array(); $d['Alert']['id'] = 1976; $d['Search']['id'] = 107; $d['AlertsElement']['ordering'] = 2; $this->Alert->create(); $this->Alert->saveAll($d); ``` I get this error - ``` Cannot use a scalar value as an array [CORE/cake/libs/model/model.php, line 1696] ``` and a row entry in alertselement with the order but the foreign keys set to 0 Any ideas ? Thanks, Alex