數據庫表我有以下設置爲我的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