使用 CakePHP 以相同形式 Update/Add/Delete 多条记录的最佳方法是什么
What is the best way to Update/Add/Delete multiple records in the same form with CakePHP
我有这个主题 table,它链接到 table Post,模型中有许多。
这是我的 $this->request->data
Array
(
[Topic] => Array
(
[id] => 1
[topic_title] => This is my topic
)
[Post] => Array
(
[1] => Array
(
[id] => 1
[title] => Blah
[message] => My message
)
[2] => Array
(
[id] => 2
[title] => Second Blah
[message] => Second My message
)
)
)
我用 :
更新它
$this->Topic->saveAssociated($this->request->data);
但是,如果我还想能够添加和删除该主题的帖子,我该怎么办?
来自 CakePHP 2 书
delete(integer $id = null, boolean $cascade = true);
Deletes the record identified by $id. By default, also deletes records
dependent on the record specified to be deleted.
For example, when deleting a User record that is tied to many Recipe
records (User ‘hasMany’ or ‘hasAndBelongsToMany’ Recipes):
- if $cascade is set to true, the related Recipe records are also deleted if the model’s dependent-value is set to true.
- if $cascade is set to false, the Recipe records will remain after the User has been deleted.
保持相同的结构,您可以执行 $this->Topic->saveAssociated($this->request->data);
,它会在数据数组中添加任何新的('id' => NULL
或未设置的)项目。
关于删除,我知道唯一会同时删除的情况是标记为 'unique' => true
的 HABTM。否则,您需要执行 $this->Post->deleteAll(array('Post.topic_id' => $unwanted_topic_id), false);
我可以考虑制作一个新数组来保留您要删除的数组并将它们作为 deleteAll 函数的条件发送。
我有这个主题 table,它链接到 table Post,模型中有许多。
这是我的 $this->request->data
Array
(
[Topic] => Array
(
[id] => 1
[topic_title] => This is my topic
)
[Post] => Array
(
[1] => Array
(
[id] => 1
[title] => Blah
[message] => My message
)
[2] => Array
(
[id] => 2
[title] => Second Blah
[message] => Second My message
)
)
)
我用 :
更新它$this->Topic->saveAssociated($this->request->data);
但是,如果我还想能够添加和删除该主题的帖子,我该怎么办?
来自 CakePHP 2 书
delete(integer $id = null, boolean $cascade = true);
Deletes the record identified by $id. By default, also deletes records dependent on the record specified to be deleted.
For example, when deleting a User record that is tied to many Recipe records (User ‘hasMany’ or ‘hasAndBelongsToMany’ Recipes):
- if $cascade is set to true, the related Recipe records are also deleted if the model’s dependent-value is set to true.
- if $cascade is set to false, the Recipe records will remain after the User has been deleted.
保持相同的结构,您可以执行 $this->Topic->saveAssociated($this->request->data);
,它会在数据数组中添加任何新的('id' => NULL
或未设置的)项目。
关于删除,我知道唯一会同时删除的情况是标记为 'unique' => true
的 HABTM。否则,您需要执行 $this->Post->deleteAll(array('Post.topic_id' => $unwanted_topic_id), false);
我可以考虑制作一个新数组来保留您要删除的数组并将它们作为 deleteAll 函数的条件发送。