Keith Power
Keith Power

Reputation: 14151

CakePHP 3 cannot save associated model

I am updating some log data in some tables. I can't save on the associated model ModulesEmployees only the top level CoursesEmployees. Cant see what is missing.

CoursesEmployeeTable.php

    $this->hasMany('ModulesEmployees', [
        'dependent' => true,
        'foreignKey' => 'courses_employee_id'
    ]);

ModulesSlidesController.php

$this->loadModel('CoursesEmployees');

$CoursesEmployee = $this->CoursesEmployees
     ->get(65, [
           'contain' => ['ModulesEmployees'],
           'where' =>[
                ['ModulesEmployees.id' => 19]
            ]
        ]);

if (!$CoursesEmployee['modules_employees'][0]['started_on']) {
    $CoursesEmployee['modules_employees'][0]['started_on'] = date('Y-m-d H:i:s');
};

$this->CoursesEmployees->save($CoursesEmployee, ['associated' => ['ModulesEmployees']]);

Returned Object

CoursesEmployee(array)
id65
employee_id3
course_id1
course_module_id1
completed_modules0
current_slide0
cid0
date_started(array)
progress0
modified(array)
created(array)
completed(false)
date_completed(null)
deleted(null)
modules_employees(array)
    0(object)
        id19
        courses_employee_id65
        course_module_id1
        started_on2015-10-04 21:00:10
        completed_on(null)
        completed(false)
        deleted(null)
[new](false)
[accessible](array)
[dirty](empty)
[original](empty)
[virtual](empty)
[errors](empty)
[repository]CoursesEmployees

Upvotes: 2

Views: 1334

Answers (1)

ndm
ndm

Reputation: 60503

Only dirty entities/properties are being saved, and what you are doing there, modifying a nested entity, will only mark that nested entity as dirty, the parent entity, CoursesEmployee will remain unchanged, and therefore the saving process won't touch the associations.

When not using the patching mechanism which automatically marks parent entity properties as dirty, then you'll have to do that on your own.

Quote from the docs:

[...]

If you are building or modifying association data after building your entities you will have to mark the association property as modified with dirty():

$company->author->name = 'Master Chef';
$company->dirty('author', true);

Cookbook > Database Access & ORM > Saving Data > Saving Associations

So in your case it's the modules_employees property that needs to be marked as dirty, like

$CoursesEmployee->dirty('modules_employees', true);

Upvotes: 4

Related Questions