保存 hasMany 总是添加记录而不是更新

saving hasMany always add record instead of updating

我有一个 hasMany 关系(假设 Post 有很多 Comments

我想同时编辑 Post 和现有的 Comment

我的代码

在我的评论edit.ctp文件中我做了

<?= $this->Form->create($post); ?>
<?= $this->Form->input('title'); ?> 
<?= $this->Form->input('title');  ?>
<?= $this->Form->input('text'); ?>
<?= $this->Form->input('comments.0.id'); ?>
<?= $this->Form->input('comments.0.text'); ?>

在我的 PostsController

$post= $this->Posts->get($id);
$post= $this->Posts->patchEntity($post, $this->request->data, ['associated' => ['Comments']]);

我的问题

现在我希望评论会更新,而不是蛋糕每次都添加新评论。

我做了什么

我尝试调试 $this->request->data 我得到了

[
    'text' => 'This is a test',
    'comments' => [
        (int) 0 => [
            'id' => '168',
            'text' => 'Comment test',

        ]
    ]
]

但是如果我调试 $post 我得到

object(App\Model\Entity\Post) {

    /* ... */
    'comments' => [
        (int) 0 => object(App\Model\Entity\Comment) {

            'text' => 'Comment test',
            '[new]' => true,
            '[accessible]' => [
                '*' => true
            ],
            '[dirty]' => [
                'text' => true
            ],
            /* ... */

        }
    ],
    /* ... */
    '[dirty]' => [
        'comments' => true,
    ],

}   

为什么当我将其 id 传递给控制器​​时评论被标记为 'new'?

当然这是我实际情况的简化版。也许问题不在上面的代码中,我必须在其他代码中查看其他地方。

我的问题是我是否犯了一些基本的方法错误。

您需要将相关数据读入您的实体以便能够对其进行修补,否则数据不会被合并,而只是被编组,因此最终被处理为 "new"。

自动加载关联数据只发生在特殊的_ids键上,并且当关联中至少有一个条目属性时,即实际上你不需要有关联数据已加载您要修补的内容,但必须有 某些内容 才能使编组器到达读取和合并数据的位置。

准确的说,comments属性中没有任何数据,编组器会从这里跳出

https://github.com/cakephp/cakephp/blob/3.2.8/src/ORM/Marshaller.php#L653-L655

我真的不知道是否存在错误,至少我想文档需要围绕这个更新,因为它们会有点误导。虽然他们确实试图解释当源实体中缺少关联数据时会发生什么,但显示的示例当前不起作用,并且他们说新实体只会为 belongsTohasOne 关联创建,这是不正确的。

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

您可能想在 GitHub 提交问题以进行澄清。

tl;博士

长话短说,包含评论,你应该是好的。

$post = $this->Posts->get($id, [
    'contain' => ['Comments']
]);
// ...