編輯:我需要幫助的是刪除topics_posts表中的主題和文章之間的所有關係,以便清理關係並刪除舊關係。然後,其餘的代碼應該工作正常,因爲所有的問題將被解決,因爲我們刪除之前添加它們的關係。更新和刪除CakePHP中的唯一連接關係
在我的CakePHP應用程序中,我有帖子和主題(主題是唯一的並且有一個id),並且它們通過處理帖子和主題之間關係的Topic_Posts彼此鏈接。
但是,如果用戶編輯具有關係的帖子並保存它,而不是修改關係,它將在Topic_posts表中複製它們,並且如果用戶從帖子中刪除主題,也不會刪除它們!
處理這個問題的最好方法是什麼?我聽說過關於刪除該帖子的所有關係,然後重新添加它們是處理所述場景的最乾淨和最好的方式,但是我又怎麼做呢?
這是處理主題保存(不檢查主題不重複)但不檢查它們是否重複的關係或刪除關係的代碼。
public function savePostTopics($postId, $topics)
{
// Explode the topics by comma, so we have an array to run through
$topics = explode(',', $topics);
// Array for collecting all the data
$collection = array();
foreach($topics as $topic)
{
// Trim it so remove unwanted white spaces in the beginning and the end.
$topic = trim($topic);
// Make it all lowercase for consistency of tag names
$topic = strtolower($topic);
// Check if we already have a topic like this
$controlFind = $this->find(
'first',
array(
'conditions' => array(
'title' => $topic
),
'recursive' => -1
)
);
// No record found
if(!$controlFind)
{
$this->create();
if(
!$this->save(
array(
'title' => $topic
)
)
)
{
// If only one saving fails we stop the whole loop and method.
return false;
}
else
{
$temp = array(
'TopicPost' => array(
'topic_id' => $this->id,
'post_id' => $postId
)
);
}
}
else
{
$temp = array(
'TopicPost' => array(
'topic_id' => $controlFind['Topic']['id'],
'post_id' => $postId
)
);
}
$collection[] = $temp;
}
return $this->TopicPost->saveMany($collection, array('validate' => false));
}
這裏有關聯:
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'
);
}
編輯:我做了以下,使兩列相互獨特:
`id` int(11) unsigned 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`)
但是當我做一個更新我得到一個SQL錯誤,所以基本上蛋糕沒有正確處理這個問題......我該如何解決這個問題,因爲它只是通過防止數據被重複部分解決問題!另外我如何處理刪除主題,因爲我想從topic_posts關係中刪除,但不知道如何做到這一點?
Database Error
Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '2-107' for key 2
SQL Query: INSERT INTO `db52704_favorr`.`topic_posts` (`topic_id`, `post_id`) VALUES (2, 107)
有沒有更新?對此非常困惑。謝謝。 – Cameron 2012-04-19 08:47:10