保存标签到CakePHP中
问题描述:
数据库表我有以下设置为我的CakePHP应用程序:保存标签到CakePHP中
Posts
id
title
content
Topics
id
title
Topic_Posts
id
topic_id
post_id
所以基本上我的主题(标签)的表都是独一无二的,并有一个ID。然后可以使用Topic_Posts连接表附加它们以发布。当用户创建新帖子时,他们将填入主题,方法是将用逗号分隔的textarea输入,然后将它们保存到主题表中(如果它们尚不存在),然后将引用保存到Topic_posts表中。我已经建立了像这样的模式:
Post模型:
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'
);
}
并为新的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
答
我会实现的方法这样的主题(型号):
/**
* 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));
}
我没有测试它,但它应该工作。
你可以调用这个AFTER保存帖子本身,为它提供帖子ID和数据数组中的主题。确保你处理该方法的返回。如果主题保存失败,这是删除整篇文章的原因?由于在cakephp中没有很好的实现回滚API,如果你愿意的话,你可能不得不从数据库中删除这个帖子。或者,您是否只向撰写帖子并记录错误的用户提供了成功信息?
顺便说一句:继CakePHP的约定模型和关联表也被命名为PostTopic和post_topic。按字母顺序;)您可能需要在项目的早期阶段更改它。
问候 func0der
真棒,工作正常。我没有改变任何我的表名或模型名称?谢谢;) – Cameron 2012-04-15 14:48:49
不,你不需要改变它。但通过cakephp约定,您应该;) 通读本:http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm(示例下方的信息框) – func0der 2012-04-16 10:20:55