我正在尝试编写一个模型方法来拉取附加到帖子的主题。数据库设置如下:
Post
id
title
Topic
id
title
Post_Topic
id
post_id
topic_id
和示例方法...
public function getPostTopics($postId)
{
$topics = $this->find('all', ...
return $topics;
}
我需要做的是在数据库中找到关系,然后以以下格式存储它们以供返回,例如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));
编辑:这是给下面的乔普的:
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'
)
)
)