When I try to add some entries into the join table of two classes, I run into issues with CakePHP.
Here is my join table:
posts_comments
id
post_id
comment_id
my post Model:
<?php
class Post extends AppModel {
var $hasManyAndBelongsTo = array('Comment')
}
?>
My Comment Model:
<?php
class Commentextends AppModel {
var $hasAndBelongsToMany = array('Post');
}
?>
My Controller:
ForumController:
function save() {
if ($this->data) {
$this->loadModel('PostComment');
$this->layout = null;
debug($this->data);
$this->PostComment->save($this->data);
}
$this->redirect(array('action' => 'view', $this->data['PostComment']['PostId']));
}
And my view.ctp:
<?php
echo $this->Form->create('PostComment', array('url' => 'save', 'id' => 'save')); ?>
echo $this->Form->hidden('PostComment.PostId', array('value' => $id));
echo $this->Form->input('PostComment.CommentId', array('label' => '', 'type' => 'select', 'multiple' => 'checkbox', 'options' => $CommentName, 'selected' => $CommentId));
echo $this->Form->submit('save', array('id' => 'submit'));
echo $this->Form->end();
?>
When I click on submit, nothing is submitted, and the redirection happens, but the data contained in my $this->data is not save in my BDD.
But what I want is that when I submit my form, I don’t want that CakePHP create a new post or a new comment, I just want a new relation between the two.
I already succeed to done it, but I used
$this->myObject->query("INSERT INTO blablabla")
The problem is that I have a multiple checkboxes, so I don’t really know how I can easily check that one box has been unchecked or checked.
You can work in a simpler way if you create another model with two hasMany relations instead of one with HABTM.
I found it is one of the simplest ways to save and retrieve data.
For more information: http://book.cakephp.org/2.0/en/models/saving-your-data.html#what-to-do-when-habtm-becomes-complicated
At the new model, you could do something like: