CakePHP方法删除连接表中的所有关系
问题描述:
在我的应用程序中,我有一个系统的文章和主题,并使用名为Topic_Post的连接表将主题附加到文章。要确保当用户编辑或删除帖子的主题是高效和干净的,我希望删除所有关系之前,我重新添加或添加新的。注意:我的意思是附加或脱离他们的帖子,而不是实际上删除主题CakePHP方法删除连接表中的所有关系
这样做的最好方法是什么?我需要将post id传递给方法,然后找到Topic Post表中具有匹配的post_id的所有记录,然后从表中删除这些记录。
这些都是协会:
Post.php
class Post extends AppModel
{
public $name = 'Post';
public $belongsTo = 'User';
public $hasMany = array('Answer');
// Has many topics that belong to topic post join table... jazz
public $hasAndBelongsToMany = array(
'Topic' => array('with' => 'TopicPost')
);
}
Topic.php
class Topic extends AppModel
{
public $hasMany = array(
'TopicPost'
);
}
TopicPost.php
class TopicPost extends AppModel {
public $belongsTo = array(
'Topic', 'Post'
);
}
在Topiic_Post表我已经作出独特的防止重复的两个外键。
id
INT(11)无符号NOT NULL的auto_increment, topic_id
INT(11)NOT NULL, post_id
INT(11)NOT NULL, PRIMARY KEY(id
) UNIQUE KEY unique_row
(topic_id
,post_id
)
而且该方法是这样的,到目前为止:
function cleanPostTopics ($postId) {
$post = $this->find('first', 'condition'=>array('Post.id'=>$postId));
}
我怎么会那么使用这个$post
到f指定TopicPost表中的所有记录,然后删除它们!请记住承认,这种方法是在一个模型中,需要能够根据我的关联与其他人交谈。
值得注意的是,如果打破显然应该防止重复发生的任何内置CakePHP逻辑,则使用以下方法插入/附加主题? http://pastebin.com/d2Kt8D2R
答
Cake会自动为你处理。删除帖子或主题时,应删除所有与HABTM相关的数据。
对于hasOne和具有许多关系,您可以在关系中定义'dependent' => true
以删除记录时删除关联的数据。
// When a Post is deleted, the associated Answer records will be as well
public $hasMany = array(
'Answer' => array(
'dependent' => true
)
);
你可以在这里阅读更多相关资讯:
- http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html
- http://book.cakephp.org/2.0/en/models/deleting-data.html
根据您的设置,您可以删除像这样相关HABTM数据:
function cleanPostTopics ($postId) {
$post = $this->find('first', 'condition'=>array('Post.id'=>$postId));
// find all HABTM with that post id
$topicsPost = $this->TopicPost->deleteAll(array(
'TopicsPost.post_id' => $postId
), false);
}
是的,但我**不**删除邮政或主题!这个方法将在保存帖子之前运行以清理关系! (我有我的理由,如OP所述) – Cameron 2012-04-19 15:53:57
啊,我没有看到这个问题。值得注意的是,当您添加新的HABTM数据时,如果您担心这个问题,则会预先彻底清除原件以防止重复。 – jeremyharris 2012-04-19 15:58:54
对我来说,它并没有被清除。它复制记录并防止我创建的外键唯一强制唯一记录,但这会导致错误,因为CakePHP仍然会尝试将它们插入表中,因此我正在尝试执行该操作。 – Cameron 2012-04-19 16:08:16