编辑:我需要帮助的是删除topic_posts表中主题和帖子之间的所有关系,以便清除关系并删除旧关系。然后剩下的代码应该正常工作,因为我们在添加之前删除了关系。
在我的CakePHP应用程序中,我有帖子和主题(主题是唯一的并且具有id),并且它们通过Topic_Posts相互链接,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错误,所以基本上Cake没有正确处理这个...我如何解决这个问题,因为它只是通过防止数据重复来部分解决问题!另外我在删除主题时如何处理,因为我希望从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)
答案 0 :(得分:1)
首先,您不需要Topic_Posts中的列id
。你应该删除它,而是使用它:
`topic_id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
PRIMARY KEY (`topic_id`, `post_id`)
这意味着添加到帖子中的每个主题只能添加一次(它实际上是你现在所拥有的,只是更加整洁)。
更新帖子时收到SQL错误的原因是因为您要将每个主题添加到Topic_Posts中的帖子,无论它们之前是否存在。
您的代码片段是:
相反,你想让它说出这样的话:
执行此操作以处理主题删除的另一种方法可能是:
您无需担心以这种方式检查Topic_Posts中该帖子的主题是否存在,因为第一步是删除该帖子的所有主题。
希望有所帮助。