我正在嘗試編寫一個模型方法,以便將帖子附加到帖子中。數據庫設置如下:使用CakePHP查找與帖子ID相關的所有主題
Post
id
title
Topic
id
title
Post_Topic
id
post_id
topic_id
和實例方法...
public function getPostTopics($postId)
{
$topics = $this->find('all', ...
return $topics;
}
我需要做的是找到在DB的關係,然後將它們存儲在爲以下格式返回例如tag1, tag2, tag3
。
誰能幫助我嗎?
這裏有關聯:
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'
);
}
以及它是如何保存到數據庫爲例(爲模型中的一個功能是如何工作的想法)擺在首位(另一個有用的禮貌人在SO)
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));
編輯:這是下面的Joep:
array(
(int) 0 => array(
'id' => '2',
'title' => 'amazing',
'TopicPost' => array(
'id' => '2',
'topic_id' => '2',
'post_id' => '107'
)
),
(int) 1 => array(
'id' => '1',
'title' => 'awesome',
'TopicPost' => array(
'id' => '1',
'topic_id' => '1',
'post_id' => '107'
)
),
(int) 2 => array(
'id' => '3',
'title' => 'jazz',
'TopicPost' => array(
'id' => '3',
'topic_id' => '3',
'post_id' => '107'
)
)
)
您可以發佈相關模型之間的關聯並指定您實際想要獲取的內容嗎?是「主題」,而不是「標籤」,還是實際上是相同的?你可以發表你想要你的返回數組的樣子的例子數組嗎? – Joep 2012-04-16 05:21:27
查看更新OP。我已經添加了很多代碼來顯示事情的工作方式。 – Cameron 2012-04-16 10:10:51
至於回報。我希望以'tag1,tag2,tag3'的格式返回一個字符串,因爲它將用於編輯視圖上textarea的值。 – Cameron 2012-04-16 10:18:26