CakePHP 3 无法保存关联模型

标签 cakephp cakephp-3.0

我正在更新一些表中的一些日志数据。我无法仅在关联模型 ModulesEmployees 上保存顶级 CoursesEmployees。看不到缺少什么。

类(class)员工表.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']]);

返回对象

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

最佳答案

仅保存脏实体/属性,而您在此处所做的操作(修改嵌套实体)只会将该嵌套实体标记为脏实体,父实体 CoursesEmployee 将保持不变,并且因此保存过程不会影响关联。

当不使用自动将父实体属性标记为脏的修补机制时,您必须自己执行此操作。

引用文档:

[...]

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 属性标记为脏,例如

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

关于CakePHP 3 无法保存关联模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32938660/

相关文章:

php - 如何在 CakePHP 3 中对模型-> 保存 () 进行 SQL 查询?

email - 使用cakephp发送邮件时出错

php - 我来自 menu.ctp 的 img 链接在 view.ctp 和 login.ctp 中消失了

php - 了解 CakePHP 模型数据中的 _ids 数组

mysql - CakePhp3 中的限制/重新采样数据

jquery - 同一 Ajax 请求中的 POST 和 Get

.htaccess - 如何禁用单个文件夹的 CakePHP 重写路由,以便它可以用作第二个应用程序的位置?

php - 在 CakePHP 中,是否可以全局设置传递给 Form helper create 方法的选项?

mysql - 如何将此 sql 查询转换为 cakephp 3 查询生成器?

php - Cakephp 3 表单,插入 FOREIGN KEY