CakePHP 3无法保存关联的模型 [英] CakePHP 3 cannot save associated model
问题描述
我正在更新某些表中的某些日志数据。我无法在关联的模型ModulesEmployees上仅保存顶级CoursesEmployees。不能看到缺少的内容。
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
CoursesEmployeeTable.php
$this->hasMany('ModulesEmployees', [
'dependent' => true,
'foreignKey' => 'courses_employee_id'
]);
ModulesSlidesController.php
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']]);
返回对象
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
推荐答案
仅保存脏的实体/属性,并且您在此所做的修改嵌套实体的操作只会标记该嵌套实体作为d不幸的是,父实体 CoursesEmployee
将保持不变,因此保存过程不会触及关联。
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.
从文档中引用:
[...]
[...]
如果要在构建后构建或修改关联数据您的
实体,您将必须使用dirty()将关联属性标记为已修改的
:
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
因此,在您的情况下,它是 modules_employees
需要标记为脏的属性,例如
So in your case it's the modules_employees
property that needs to be marked as dirty, like
$CoursesEmployee->dirty('modules_employees', true);
这篇关于CakePHP 3无法保存关联的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!