I have two models with a HABTM (Has and belongs to many) relationship: Qsets and Questions.
The following action (in QsetsController.php) should result in a new row in the qsets_questions table, with the new question appearing in the new qset. But instead it updates existing rows, resulting in that question begin taken from a previous qset and added to the new one.
What am I doing wrong?
public function admin_add_question( $qset_id, $question_id) {
//find the qset...
$qset = $this->Qset->find('first', array('id'=>$qset_id));
$this->Qset->QsetsQuestion->create();
$data = array(
"Qset"=> array ("id"=>$qset_id),
"Question"=>array ("id"=>$question_id)
);
Controller::loadModel('Question');
$r= $this->Question->save($data);
$this->Session->setFlash('Question id['.$question_id.'] added.');
$this->redirect( $this->referer() );
}
In case it wasn't clear from my description, here happens:
Before adding a question...
**Qset 1**
Question 1
Question 2
**Qset 2**
Question 3
Question 4
What should happen when adding Question 2 to Qset 2
**Qset 1**
Question 1
Question 2
**Qset 2**
Question 3
Question 4
Question 2
What happens instead...
**Qset 1**
Question 1
<----removed
**Qset 2**
Question 3
Question 4
Question 2
update: Here's a dump of my qsets_questions table:
CREATE TABLE `qsets_questions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`question_id` int(11) NOT NULL,
`qset_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=64 ;
Solution:
Here's the working version, thanks to @nuns
public function admin_add_question( $qset_id, $question_id) {
$this->Qset->QsetsQuestion->create();
$data = array(
"qset_id"=>$qset_id,
"question_id"=>$question_id
);
Controller::loadModel('Question');
$this->Question->QsetsQuestion->save($data);
$this->Session->setFlash('Question id['.$question_id.'] added.');
$this->redirect( $this->referer() );
}