Saving tags into a database table in CakePHP

Posted by Cameron on Stack Overflow See other posts from Stack Overflow or by Cameron
Published on 2012-04-15T11:26:03Z Indexed on 2012/04/15 11:29 UTC
Read the original article Hit count: 231

Filed under:
|

I have the following setup for my CakePHP app:

Posts
id
title
content

Topics
id
title

Topic_Posts
id
topic_id
post_id

So basically I have a table of Topics (tags) that are all unique and have an id. And then they can be attached to post using the Topic_Posts join table. When a user creates a new post they will fill in the topics by typing them in to a textarea separated by a comma which will then save these into the Topics table if they do not already exist and then save the references into the Topic_posts table. I have the models set up like so:

Post model:

class Post extends AppModel
{
    public $name = 'Post';

    public $hasAndBelongsToMany = array(
        'Topic' => array('with' => 'TopicPost')
    );
}

Topic model:

class Topic extends AppModel
{
    public $hasMany = array(
        'TopicPost'
    );
}

TopicPost model:

class TopicPost extends AppModel {
    public $belongsTo = array(
        'Topic', 'Post'
    );
}

And for the New post method I have this so far:

public function add()
{
    if ($this->request->is('post'))
    {
        //$this->Post->create();

        if ($this->Post->saveAll($this->request->data))
        {

            // Redirect the user to the newly created post (pass the slug for performance)
            $this->redirect(array('controller'=>'posts','action'=>'view','id'=>$this->Post->id));
        }
        else
        {
            $this->Session->setFlash('Server broke!');
        }
    }
}

As you can see I have used saveAll but how do I go about dealing with the Topic data?

© Stack Overflow or respective owner

Related posts about php

Related posts about cakephp