数据库表我有以下设置为我的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
真棒,工作正常。我没有改变任何我的表名或模型名称?谢谢;) – 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