3
votes

Question related to HABTM has been posted in some good numbers on stackoverflow but I am still looking for a solution to my problem.

I am creating an application that allows for creation of topics based on a particular subcategory. While adding a topic the user is asked for tags (on the same form). Now when the user has finished adding tags to the topic on the click of Add button the topic is successfully added but tags are not.

I have created the join table for both topics and tags as tbl_tags_topics. (as defined in the conventions of cakephp) and defined the 'hasAndBelongsToMany' array properly in both the models of topics and tags.

What steps am I missing now.?

I have one more question related to this but I will post it when I will be able to send tags related to a topic successfully to the database. (the functionality is similar to that of stackoverflow's tags adding and attaching)

any help is greatly appreciated., also let me know of any good tutorials on HABTM if you find one.

Thanks

2
Are you using the Security Component?powtac
no, I am not using any Security Component right now. It(Auth) will be implemented when this(HABTM) feature is done.Gaurav Sharma

2 Answers

5
votes

When you save one of the fields, you pass parameters like that :

$this->Model->save(
    'Model' => array('id' => 1, 'name' => 'one random field)
);

If you have tags, which is a HABTM, you could do the following :

$this->Model->save(
    'Model' => array('id' => 1, 'name' => 'one random field'),
    'Tag' => array('Tag' => array(1))
);

However there's a problem with this native feature, it's that every time you save your object, you need to pass every tag to the saved array. Otherwise, they'll all be removed before to be readded.

However you can find on bakery, a plugin called extended associations.

Using it, you would do :

$this->Model->habtmAdd('Tag', 1, 1);

Where the first "1" is the model's object id. And the second is the tag's object id.

And to remove a tag :

$this->Post->habtmDelete('Tag', 1, 1); 
3
votes

With the help of Mr. Stornvig, I was able to solve my problem. Here is the link that describes the complete procedure of how to achieve such functionality in cakephp. This is an awesome tutorial for learning more about HABTM relationship.

For version 1.3 I found out this technique to be useful. Here are the steps:

after defining the HABTM relationship array in both the models

create your form like this

echo $form->create('Job');
echo $form->input('title');
echo $form->input('description');
echo $form->input('location');
echo $form->input('Category');//note the caps and single plural
$form->end('Submit');

and then in the controller add method simply use the

saveAll($this->data)

and the join table will be populated with the required records also.

more info