编辑:我需要帮助的是删除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