I have hasMany relation between Employee and Schedule.
When editing an Employee, I manage to get the current schedule and populate my form.
Upon saving, I use:
if ($this->Employee->save($this->request->data)) {
$this->Employee->Schedule->save($this->request->data, $validate = false);
....
}
Employee data saves fine, but Schedule record is left untouched.
I’m actually providing the id as part as the array. On my controller, debug($this->request->data) shows:
array(
'Employee' => array(
'emp_position' => '1',
'name' => 'the name',
'emp_gender' => '1',
'emp_father' => '',
'emp_mother' => '',
'emp_dob' => 'October 13, 1964',
...
..
),
'Schedule' => array(
(int) 0 => array(
'id' => '7',
'ho_lu2' => '10:00',
'ho_ma2' => '01:00',
'ho_mi2' => '00:00',
'ho_ju2' => '00:00',
'ho_vi2' => '00:00',
'ho_do4' => '00:00'
)
)
)
.
***************** Update ************
I think it has to do with foreign keys being different on my two tables
My employees table:
CREATE TABLE IF NOT EXISTS `employees` (
`id` int(5) DEFAULT NULL,
`emp_appserial` int(5) unsigned NOT NULL AUTO_INCREMENT,
...
(Please note that on Employee table, emp_appserial is my pk autoincr, and employee_id can be null for some records)
My Schedules table:
CREATE TABLE IF NOT EXISTS `schedules` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`name` varchar(50) DEFAULT NULL,
`employee_id` int(5) unsigned NOT NULL,
...
Since I’ve linked these tables using a different field, i use foreignKey:
On my model, I linked:
Employee Model:
var $hasMany = array(
'Schedule' => array(
'foreignKey' => 'employee_id', //(field on Schedule)
'dependent' => true
)
);
public $primaryKey = 'emp_appserial'
Schedule Model:
var $belongsTo = array('Employee',
'Employee' => array(
'foreignKey' => 'emp_appserial' //(field on Employee)
)
);
My posted data now includes employee_id for Schedule, and emp_appserial for Employee
array(
'Employee' => array(
'id' => null,
'emp_appserial' => '119'
...
),
'Schedule' => array(
(int) 0 => array(
'id' => '6',
'name' => 'segundo horario',
'emp_appserial' => '119',
'employee_id' => '119'
)
)
)
(tried appending to Schedule both id and serial to try my luck- not good.)
Any help greatly appreciated.
Thanks a lot !
“As a rule, when working with hasOne, hasMany, and belongsTo associations, its all about keying” – CakePHP Manual.
Your Employee array has to pass an id and the schedule array needs to have an employee_id so cake knows what are the linked models.