When updating the HABTM records, all the associated records must first get deleted and then the new records should be inserted. Sticking to this theory,
If Post HABTM keywords, then all the records in association table for a particular post should be deleted before adding new keywords.
For ex. if I edit post id=1, then query to fetch association records should be:
SELECT * FROM keywords_posts WHERE post_id = '1'
and not
SELECT * FROM keywords_posts WHERE post_id = '1' AND keyword_id = 1 LIMIT 1
The first query will return all the records in association table which should then be deleted by delete function in AkHasAndBelongsToMany.php
I have modified the delete function as follows:
if(!in_array($id, $ids_to_skip)){
/*$JoinObjectToDelete =& $this->JoinObject->findFirstBy(
$options['foreign_key'].' AND '.$options['association_foreign_key'],
$this->Owner->getId(), $id);*/
$JoinObjectToDelete =& $this->JoinObject->findBy(
$options['foreign_key'],
$this->Owner->getId());
foreach ($JoinObjectToDelete as $val) {
if($val->destroy()){
$items_to_remove_from_collection[] = $id;
}else{
$success = false;
}
}
}
I know I should have written tests and submitted the patch :) but if someone can confirm the correctness of this code then I will do so soon.
Aditya, have a look at new test case for the habtm relationship
I've commited the changes on rev.328, thanks your your help on this one.
Bermi -
The query is still not correct. In WHERE it is still checking with both the foreign keys. The only difference is LIMIT keyword is now removed and findAllBy is used. But essentially the query will always return only one record for given combination of the two foreign keys.
The new query after updating SVN looks like:
SELECT * FROM keywords_posts WHERE post_id = '1' AND keyword_id = '2'
Whereas it should be
SELECT * FROM keywords_posts WHERE post_id = '1'
then only findAllBy will have a meaning.
After some more debugging and testing my app I noticed the actual problem.
While editing if I select a completely different set of keywords then everything works file.
For ex. I have keywords "php", "mysql" and
while editing I change it to "framework", "lamp" then everything works as expected.
BUT if I change the keywords to "mysql", "framework" (notice that mysql is common) then keyword mysql gets duplicated. The previous entry remains as it is and a new entry also gets added.
With this finding, my above comment gets void and the only thing needs to be corrected is Point 2.
To avoid duplicated entries at habtm associations
var $has_and_belongs_to_many = array(
'keywords' => array('unique'=>true)
);
Hey Bermi - this worked. Thanks a lot.
Oops! I just noticed that salavert gave me the solution. THANKS A LOT salavert. :D Thanks to bermi as well for fixing the problem.
1 to 7 of 7