Friday, November 28, 2008

Problem with HABTM relationship...

Hello,

This is my problem:

I have a user model which is linked to a role model via a HABTM
association.

When a new record is added all the associations are added correctly,
the problem is when I delete a record, the associated records are not
deleted as expected.

Cake also showed the following error:

Warning (512): SQL Error: 1054: Unknown column 'RolesUser.id' in
'field list' [CORE\cake\libs\model\datasources\dbo_source.php, line
521]

So to solve the problem I over wrote the following function from the
core model file located at: app\cake\libs\model\model.php

/**
* Cascades model deletes to HABTM join keys.
*
* @param string $id ID of record that was deleted
* @return void
* @access protected
*/
function _deleteLinks($id) {
$db =& ConnectionManager::getDataSource($this->useDbConfig);
pr($this->hasAndBelongsToMany);
foreach ($this->hasAndBelongsToMany as $assoc => $data) {
$records = $this->{$data['with']}->find('all', array(
'conditions' => array($data['foreignKey'] => $id),
'fields' => $this->{$data['with']}->primaryKey,
'recursive' => -1
));
if (!empty($records)) {
foreach ($records as $record) {
$this->{$data['with']}->delete($record[$this->{$data['with']}-
>alias][$this->{$data['with']}->primaryKey]);
}
}
}
}

------------------------------------------------
with this function in app_model.php
/**
* Cascades model deletes to HABTM join keys.
*
* @param string $id ID of record that was deleted
* @return void
* @access protected
*/
function _deleteLinks($id) {
foreach ($this->hasAndBelongsToMany as $assoc => $data) {
$records = $this->{$data['with']}->find('all', array(
'conditions' => array($data['foreignKey'] => $id),
//'fields' => $this->{$data['with']}->primaryKey,
'fields' => $data['foreignKey'],
'recursive' => -1
));

if (!empty($records)) {
foreach ($records as $record) {
//added this line;
$this->{$data['with']}->primaryKey = $data['foreignKey'];
$this->{$data['with']}->delete($record[$this->{$data['with']}-
>alias][$this->{$data['with']}->primaryKey]);
}
}
}
}

It now works fine, but I am not really if can consider the problem
solved.

Can someone with more experience take a look and let me that it will
not cause any issues.

I did rather not touch the Cake core files...

Many thanks in advance.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "CakePHP" group.
To post to this group, send email to cake-php@googlegroups.com
To unsubscribe from this group, send email to cake-php+unsubscribe@googlegroups.com
For more options, visit this group at http://groups.google.com/group/cake-php?hl=en
-~----------~----~----~----~------~----~------~--~---

No comments: