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


CakePHP method to remove all relationships in a join table

在我的应用程序中,我有一个帖子和主题系统,并使用名为Topic_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) 不为空, post_id int(11) 不为空, 主键 ( id ), 唯一密钥unique_rowtopic_idpost_id

到目前为止,方法如下:

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

那么我将如何使用此$post查找 TopicPost 表中的所有记录,然后删除它们!请记住承认此方法位于其中一个模型中,并且需要能够根据我的关联与其他模型进行对话。

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

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
  )
);

您可以在此处阅读有关它的更多信息:

  • 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);
}