2012-04-19 98 views
0

在我的應用程序中,我有一個系統的文章和主題,並使用名爲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_rowtopic_idpost_id

而且該方法是這樣的,到目前爲止:

function cleanPostTopics ($postId) { 

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

} 

我怎麼會那麼使用這個$post到f指定TopicPost表中的所有記錄,然後刪除它們!請記住承認,這種方法是在一個模型中,需要能夠根據我的關聯與其他人交談。

值得注意的是,如果打破顯然應該防止重複發生的任何內置CakePHP邏輯,則使用以下方法插入/附加主題? http://pastebin.com/d2Kt8D2R

回答

0

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

你可以在這裏閱讀更多相關資訊:

根據您的設置,您可以刪除像這樣相關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); 

} 
+0

是的,但我**不**刪除郵政或主題!這個方法將在保存帖子之前運行以清理關係! (我有我的理由,如OP所述) – Cameron 2012-04-19 15:53:57

+0

啊,我沒有看到這個問題。值得注意的是,當您添加新的HABTM數據時,如果您擔心這個問題,則會預先徹底清除原件以防止重複。 – jeremyharris 2012-04-19 15:58:54

+0

對我來說,它並沒有被清除。它複製記錄並防止我創建的外鍵唯一強制唯一記錄,但這會導致錯誤,因爲CakePHP仍然會嘗試將它們插入表中,因此我正在嘗試執行該操作。 – Cameron 2012-04-19 16:08:16