cakephp 在保存关联后获取实体的脏字段

ljsrvy3e  于 2022-11-12  发布在  PHP
关注(0)|答案(2)|浏览(201)

我尝试记录应用程序中的每个操作(插入/更新/删除),并且在保存实体后获取dirtyoriginal值。问题是相关实体的所有值都返回为脏值,甚至is_new标志也设置为true,但实际上我正在更新。是什么导致了这种行为,我如何避免?
示例:

$data = [
    'name'      => $name,
    'something' => $something,
    'Table1'    => [
        'id'     => $idWhereUpdatingTable1,
        'field1' => $field1,
        'field2' => $field2,
    ],
    'Table2'    => [
        'id'     => $idWhereUpdatingTable2,
        'field3' => $field3,
        'field4' => $field4,
    ],
];
$options = ['associated' => ['Table1', 'Table2']];

$updatedEntity = $this->patchEntity($entity, $data, $options);
$save = $this->save($updatedEntity);

// Successfully logging the changes in the main entity

// Trying to log the changes in the associated entities
foreach($save->table1 as $entity)
{
    // everything here is set to dirty (even ID field but it's not an insert) and I'm not able to fetch the updated fields only. Also getOriginal() doesn't return the old values.
}
rbpvctlc

rbpvctlc1#

我对实体中的dirty()函数做了一些研究,根据API,如果你不显式地要求它检查属性,那么它只会告诉你实体是否有任何脏属性。
这么做
$entity->dirty('title');告诉你瓷砖是否脏了,但运行$entity->dirty();只会告诉你实体中是否有任何属性脏了。
http://api.cakephp.org/3.1/class-Cake.ORM.Entity.html#_dirty

rfbsl7qr

rfbsl7qr2#

您可能希望根据实体中的字段是否已更改来使代码具有条件。
例如,您可能只想在字段变更时验证字段:

// See if the title has been modified. CakePHP version 3.5 and above
$entity->isDirty('title');

// CakePHP 3.4 and Below use dirty()
$entity->dirty('title');

相关问题