Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7814913
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T05:21:14+00:00 2026-06-02T05:21:14+00:00

I’m trying to write a model method that will pull topics attached to a

  • 0

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

EDIT: This is for Joep below:

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'
        )
    )
)
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T05:21:16+00:00Added an answer on June 2, 2026 at 5:21 am

    I’ll be assuming this function is in the PostModel.

    function getTagsByPost($postId) {
        $this->Behaviors->attach('Containable') //Remove this if you're already using ContainableBehavior
        $result = $this->find(
            'first',
            array(
                'conditions' => array(
                    'Post.id' => $postId
                ),
                'contain' => array(
                    'Topic' => array(
                        'order' => 'Topic.title ASC'  //Edit this value to change your sorting (or remove the array containing 'order' to disable sorting completely)
                    )
                )
            )
        );
        $returnString = '';
        foreach($result['Topic'] as $num => $topic) {
            $returnString .= $topic['title'];
            $nextNum = $num+1;
            if(isset($result['Topic'][($nextNum])) {
                $returnString .= ', ';
            }
        }
        return $returnString;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to create an if statement in PHP that prevents a single post
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I need a function that will clean a strings' special characters. I do NOT
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I've got a string that has curly quotes in it. I'd like to replace
I am trying to render a haml file in a javascript response like so:

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.