Hi, I have searched this forum and read the manuals, and finally got my code working, BUT am I doing this right or have I just found a cludge by dumb luck?
I have 2 tables Questions and Games joined correctly thru games_questions table. Users can attach or detach Questions from a Game (drag 'n drop) but I was having trouble writing/deleting into the games_questions x-ref. The post on this forum titled "not understanding simple HABTM save/ delete" by Ryan McKillen gave me my solution (adapted version below), along with http://teknoid.wordpress.com/2008/07/11/notes-on-cakephp-habtm-part-2-saving-data/ So my question is: Do I have to read the existing relationships ($this- >Question->find) just to insert/remove a new relationship? I have used containable to make the read as efficient as possible, but it seems wasteful. If I don't populate the array then all existing relationships get replaced by the new one, and this is the only way I found to get it to work. //Read the existing Question to get current relationships... $data=$this->Question->find('first',array( 'conditions'=>array('Question.id'=>$q_id), 'contain'=>array('Game.id') )); // Extract only the Game's ids into an array $existing=Set::extract('/Game/id',$data); // Build a new datastructure $this->data['Question']['id']=$q_id; $this->data['Game']=$existing; $this->data['Game'][]=$target_game_id']; if ($this->Question->save($this->data)){ /// Yay it saved } I haven't written the code to Detach a Question from a Game yet, but unless I hear otherwise I guess I'll do something similar: 1. Read existing relationships 2. Remove the target from the array 3. Save the Question (the delete would be implied) Somehow it seems unnatural IMO to use Save on a model to Insert, Save, and Delete HABTM relationships, but I'll get used to it, if that's what it takes. Thanks folks. --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "CakePHP" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/cake-php?hl=en -~----------~----~----~----~------~----~------~--~---
