在CakePHP 2中使用“软删除”与HABTM关系

时间:2012-05-29 12:11:37

标签: php cakephp cakephp-2.0 has-and-belongs-to-many cakephp-appmodel

使用CakePHP 2.x中的HABTM表,使用“软删除”技术的最佳方法是什么(即在连接表中具有“删除”布尔字段),以便在删除关联时“删除”字段仅被更新为“1”而不是被删除的行?

一个例子是电影数据库,它可以是一个或多个类型的一部分。所有表都有一个“已删除”字段,因此不会从数据库中删除任何数据,只有“已删除”字段会根据需要更新为1或0:

电影

  • ID
  • 名称
  • 删除

类型

  • ID
  • 名称
  • 删除

GenreMovie

  • genre_id
  • movie_id
  • 删除

添加或编辑电影时,用户可以选择一个或多个类型来关联电影。如果从电影中删除先前关联的类型,则“已删除”将设置为“1”。如果相同的类型然后与电影重新关联,它将更新回“0”。

我们尝试过CakeDC的Utils插件中的SoftDelete行为 - https://github.com/CakeDC/utils - 这对Movie和Genre非常有用,但对我们来说似乎不适用于连接表GenreMovie,它继续完全有行删除。

1 个答案:

答案 0 :(得分:0)

你可以在你的人际关系中建立一个deleteQuery

另外,为防止删除连接表中的记录,请查看:

  

unique:boolean或string keepExisting。

   If true (default value) cake will first delete existing relationship records in the foreign keys table before inserting new ones. Existing associations need to be passed again when updating.
   When false, cake will insert the relationship record, and that no join records are deleted during a save operation.
   When set to keepExisting, the behavior is similar to true, but existing associations are not deleted.