有没有办法让saveAll()删除无关的对象? [英] Is there a way to make saveAll() remove extraneous objects?

查看:133
本文介绍了有没有办法让saveAll()删除无关的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主机对象有多个与之关联的选项对象。在编辑表单中,用户可以(删除)选择选项并保存新的关联集。这是使用saveAll()对发布的数据实现的。结果是

My host object hasMany option objects associated with it. In the edit form, users can (de)select options and save that new set of associations. This is implemented using saveAll() on the posted data. The result is that


  • 主机(主)对象已更新,

  • 包括在先前关联和新关联中的对象被更新,并且创建未包括在先前关联中但被包括在新关联中的

  • 选项对象。

但不会发生的是



问题:可以将包含在先前关联中但未包含在新关联中的对象删除。 saveAll()这样做,以及数据结构如何实现这种效果?

Question: Can saveAll() do that as well, and how would the data structure have to look like to achieve this effect?

相关信息:

我的代码来处理编辑表单实际上更复杂(因此我没有在这里引用),但它导致数据结构如书中描述:

My code to handle the edit form is actually more complex (hence I haven't quoted it here) but it results in the data structure as described in the book:

( [Host] => ( ... host object fields ... ),
  [Option] => ( [0] => ( ... first option object fields ... ),
                ...
                [n] => ( ... nth option object fields ... )
              )
)

现在,如果原来的主机有一个关联的选项,不包括在0..n数组,然后saveAll()将不会检测到这个,并不会删除该关联对象。

Now, if the original host had an associated option that is not included in the 0..n array then saveAll() won't detect this and won't delete that associated object.

不确定这是否相关,但我使用的是CakePHP 1.3。

Not sure if this is relevant but I am using CakePHP 1.3 .

推荐答案

HABTM 删除所有关联的记录,然后重新创建所需的内容。由于 Pawel Mysior 建议,您可以通过手动实现 hasMany 删除紧接在保存之前的相关联记录。但是,危险是,保存失败,你失去了以前的状态。

HABTM deletes all associated records then recreates what is needed. As PawelMysior suggests, you could achieve this with your hasMany by manually deleting the associated records immediately before the save. The danger, though, is that the save fails you lose the previous state.

我会使用 GJ 的解决方案,并在成功保存后删除它们,而是循环使用一个冗余ID数组,并使用Cake的Model-> del()方法。这样就保留了所有内置的错误处理。

I would go with a variant of GJ's solution and delete them after a successful save, but instead loop over an array of redundant IDs and use Cake's Model->del() method. This way you retain all the built-in error handling.

这篇关于有没有办法让saveAll()删除无关的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆