1

我有一段hasMany关系(比如说PosthasMany 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那么,当我将评论传递给控制器​​时,为什么评论会被标记为“新”呢?

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

我的问题是我是否在做一些基本的方法错误。

4

1 回答 1

2

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

自动加载关联数据只发生在特殊_ids键上,并且当关联属性中至少有一个条目时,即实际上您不需要加载要修补的关联数据,但必须有一些东西让编组器到达正在读取和合并数据的点。

准确的说,在comments属性中没有任何数据的情况下,marshaller 会从这里走出

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

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

食谱 > 数据库访问和 ORM > 保存数据 > 修补 HasMany 和 BelongsToMany

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

tl;博士

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

$post = $this->Posts->get($id, [
    'contain' => ['Comments']
]);
// ...
于 2016-05-09T12:07:22.553 回答