投稿に添付されたトピックを取得するモデル メソッドを作成しようとしています。DBの設定は次のとおりです。
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'
)
)
)