Monday, April 16, 2012

Find all topics related to a post id using CakePHP

I'm trying to write a model method that will pull topics attached to a post. The DB setup is as follows:



Post
id
title

Topic
id
title

Post_Topic
id
post_id
topic_id


and the example method...



public function getPostTopics($postId)
{
$topics = $this->find('all', ...
return $topics;
}


What I need to do is find the relationships in the DB and then store them in the following format for the return e.g. tag1, tag2, tag3.



Can anyone help me out?



Here are the associations:



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'
);
}


and for an example of how it's saved into the Database (to give an idea of how a function in the model works) in the first place (courtesy of another helpful person on 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));




No comments:

Post a Comment