我的CakePHP应用程序有以下设置:
Posts
id
title
content
Topics
id
title
Topic_Posts
id
topic_id
post_id
所以基本上我有一个主题(标签)表,它们都是唯一的,并且有一个id。然后可以使用Topic_Posts连接表将它们附加到post。当用户创建新帖子时,他们将通过键入以逗号分隔的文本区来填写主题,然后将这些主题保存到主题表中(如果它们尚不存在),然后将引用保存到Topic_posts表中。我的模型设置如下:
发布模型:
class Post extends AppModel
{
public $name = 'Post';
public $hasAndBelongsToMany = array(
'Topic' => array('with' => 'TopicPost')
);
}
主题模型:
class Topic extends AppModel
{
public $hasMany = array(
'TopicPost'
);
}
TopicPost模型:
class TopicPost extends AppModel {
public $belongsTo = array(
'Topic', 'Post'
);
}
对于New post方法,到目前为止我有这个:
public function add()
{
if ($this->request->is('post'))
{
//$this->Post->create();
if ($this->Post->saveAll($this->request->data))
{
// Redirect the user to the newly created post (pass the slug for performance)
$this->redirect(array('controller'=>'posts','action'=>'view','id'=>$this->Post->id));
}
else
{
$this->Session->setFlash('Server broke!');
}
}
}
正如您所看到的,我使用过saveAll
但是如何处理主题数据呢?
我见过这样的事情:http://bakery.cakephp.org/articles/dooltaz/2007/05/02/simple-tagging-behavior但我希望这样做更简单,更现代(那篇文章是2007年),我也在使用CakePHP 2.1
答案 0 :(得分:3)
我会在Topic(Model)中实现一个方法,如下所示:
/**
* This methods saves the topics coming from a post save and associates them with the right post.
*
* @param string $postId The post id to save associations to.
* @param string $topics A comma seperated list of topics to save.
* @param bool Save of all topics succeeded (true) or not (false).
*/
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);
// 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));
}
我没有测试它,但它应该可以工作。
您可以在保存帖子之后调用此方法,为其提供帖子ID和数据数组中的主题。确保您处理该方法的返回。如果主题保存失败,这是删除整个帖子的原因吗?由于cakephp中没有很好的实现回滚api,如果你愿意,你可能不得不从数据库中删除帖子。或者您只是向撰写帖子的用户发送成功消息并记录错误?
顺便说一句:遵循cakephp惯例,模型和关联表也必须命名为 PostTopic 和 post_topic 。按字母顺序;)您可能希望在项目的早期状态中更改它。
问候 func0der