CakePHP 3 - patchEntities()的表单数据格式

时间:2018-02-23 10:41:22

标签: forms cakephp orm cakephp-3.0

我的问题非常简单:如何使用patchEntities()修补多个实体,表单数据应如何(例如,名称键应该是什么样的)?

我读过 Cookbook > Database Access & ORM > Saving Data > Converting Multiple Records ,但没有明确提及如何使用它。

此结构适用于newEntities()

        $data = [
            '0' => ['field1' => '...', /* ... */],
            '1' => ['field1' => '...', /* ... */],
            '2' => ['field1' => '...', /* ... */]
        ];

表格如下:

<?= $this->Form->input('0.field1', /* ... */) ?>
<?= $this->Form->input('1.field1', /* ... */) ?>
...

但是,使用'id.field1'的相同结构不会对patchEntities()中的实体进行任何更改。

1 个答案:

答案 0 :(得分:2)

表单数据应该看起来相同,但它应该包括记录主键,以便编组人员可以映射相应记录上的数据。表单输入中的前导数字不是主键(id),而只是结果数组索引。

文档可以在那里使用一点点更新来包含patchEntities(),现在“修补HasMany和BelongsToMany ”部分中只隐藏了一小段。

<强> Cookbook > Database Access & ORM > Saving Data > Patching HasMany and BelongsToMany

因此表单应该类似于:

<?= $this->Form->input('0.id', /* ... */) ?>
<?= $this->Form->input('0.field1', /* ... */) ?>
<?= $this->Form->input('1.id', /* ... */) ?>
<?= $this->Form->input('1.field1', /* ... */) ?>
<!-- ... -->

生成如下数据集:

$data = [
    '0' => ['id' => '...', 'field1' => '...', /* ... */],
    '1' => ['id' => '...', 'field1' => '...', /* ... */],
    // ...
];

然后可以修补给定的实体:

$original = $this->Table->find()->toArray();
$patched = $this->Table->patchEntities($original, $data);