CakePHP方法删除连接表中的所有关系

时间:2012-04-19 15:36:23

标签: php cakephp

在我的应用程序中,我有一个帖子和主题系统,并使用名为Topic_Post的连接表将主题附加到帖子。要确保当用户编辑或删除帖子的主题时效率高且干净,我想在重新添加或添加新关系之前删除所有关系。注意:我的意思是将它们附加或分离到帖子和实际上并未删除主题

这样做的最佳方式是什么?我需要将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)unsigned NOT NULL auto_increment,   topic_id int(11)NOT NULL,   post_id int(11)NOT NULL,   PRIMARY KEY(id),   独特的钥匙unique_rowtopic_idpost_id

到目前为止,方法是这样的:

function cleanPostTopics ($postId) {

$post = $this->find('first', 'condition'=>array('Post.id'=>$postId));

}

然后我如何使用此$post查找TopicPost表中的所有记录,然后删除它们!请记住,此方法属于其中一个模型,需要能够根据我的关联与其他模型进行交流。

值得注意的是,如果破坏任何内置的CakePHP逻辑显然应该防止重复发生,我会使用以下方法插入/附加主题? http://pastebin.com/d2Kt8D2R

1 个答案:

答案 0 :(得分:1)

Cake会自动为您处理。删除帖子或主题时,应删除所有与HABTM相关的数据。

对于hasOne和hasMany关系,您可以在关系中定义'dependent' => true,以便在删除记录时删除相关数据。

// When a Post is deleted, the associated Answer records will be as well
public $hasMany = array(
  'Answer' => array(
    'dependent' => true
  )
);

您可以在此处阅读更多信息:

根据您的设置,您可以删除相关的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);

}