【问题标题】:saving hasMany always add record instead of updating保存 hasMany 总是添加记录而不是更新
【发布时间】:2016-09-03 20:18:45
【问题描述】:

我有一个hasMany 关系(比如说Post hasMany 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']]);

我的问题

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

我做了什么

我尝试调试$this-&gt;request-&gt;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 传递给控制器​​时,为什么评论会被标记为“新”?

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

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

【问题讨论】:

  • 您可以删除旧记录以保存新记录。

标签: php cakephp cakephp-3.2


【解决方案1】:

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

自动加载关联数据仅适用于特殊的_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;博士

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

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

【讨论】:

  • 谢谢,效果很好。不仅手册的那部分令人困惑,而且this one imho。
  • @arilia 如果该示例包含读取数据的代码肯定会有所帮助,因为您实际上 必须 读取数据,而这不是错误。
  • @arilia 我已经在cakephp/docs 上打开了一个问题。 github.com/cakephp/docs/issues/3952
  • 感谢 ndm。我会自己开一张票,但我不太擅长用英语写作,我不会那么清楚
猜你喜欢
  • 2022-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-18
相关资源
最近更新 更多