CakePHP的HABTM:编辑一个项目casuses HABTM排得到重建,破坏了额外的数据
-
21-09-2019 - |
题
我在使用CakePHP中我HABTM关系麻烦。
我有两种型号,像这样:Department
HABTM Location
。一个大公司有很多建筑,每个建筑提供服务的数量有限。每个建筑也有自己的网页,所以除了HABTM关系本身,每个HABTM行也有一个url
字段,用户可以访问找到他们感兴趣,以及它如何在建筑物运行他们”业务附加信息重新感兴趣的
我已经建立了模型,像这样:
<?php
class Location extends AppModel {
var $name = 'Location';
var $hasAndBelongsToMany = array(
'Department' => array(
'with' => 'DepartmentsLocation',
'unique' => true
)
);
}
?>
<?php
class Department extends AppModel {
var $name = 'Department';
var $hasAndBelongsToMany = array(
'Location' => array(
'with' => 'DepartmentsLocation',
'unique' => true
)
);
}
?>
<?php
class DepartmentsLocation extends AppModel {
var $name = 'DepartmentsLocation';
var $belongsTo = array(
'Department',
'Location'
);
// I'm pretty sure this method is unrelated. It's not being called when this error
// occurs. Its purpose is to prevent having two HABTM rows with the same location
// and department.
function beforeSave() {
// kill any existing rows with same associations
$this->log(__FILE__ . ": killing existing HABTM rows", LOG_DEBUG);
$result = $this->find('all', array("conditions" =>
array("location_id" => $this->data['DepartmentsLocation']['location_id'],
"department_id" => $this->data['DepartmentsLocation']['department_id'])));
foreach($result as $row) {
$this->delete($row['DepartmentsLocation']['id']);
}
return true;
}
}
?>
在控制器是完全不感兴趣。
<强>的问题:强>
如果我编辑Location
的名字,都被链接到DepartmentsLocation
的Location
s都是空的URL重新创建。由于车型指定唯一是真实的,这也导致所有新行来覆盖旧行,基本上摧毁了所有的URL。
我想知道两件事情: 我能停止?如果是的话,如何?
和上技术含量更低,更whiney记:为什么这甚至会发生?看来奇怪的,我认为通过蛋糕编辑字段应该造成这么大的麻烦,我可以轻松地去通过phpmyadmin,编辑Location
名字在那里,并得到准确的结果我期望的那样。为什么CakePHP的触摸HABTM数据时,我只需要编辑某行的字段?它甚至不是一个外键!
解决方案
从食谱的第一问题是:
默认情况下在保存时 HasAndBelongsToMany关系,蛋糕 将删除连接表中的所有行 之前保存新的。
我不明白为什么蛋糕正试图保存HABTM数据,即使你没有在你的数据的外键,但有一个简单的解决方案可为。只需摧毁了该协会保存调用:
$this->Location->unbindModel(
array('hasAndBelongsToMany' => array('Department'))
);
其他提示
我在想的一个原因这可能发生。当您检索Location
,你还检索locations_departments
数据。当你做一个save($this->data)
看起来数组中的模型和保存它们。
要解决这个问题的方法是在recursive
实体(模型)设置的 -1 的或 0 的(尝试,我不知道,只是打印出来的数据看到什么出来)。可以将其设置在模型:var $recursive = -1;
或在控制器方法(动作):$this->ModelName->recursive = -1;
更多关于递归: http://book.cakephp.org/view/439/recursive
这真是类似于 harpax 的建议,只是如果你并不需要这些数据,就告诉蛋糕,所以它不会把它拿来。
麻烦的是,保存Location
的时候,你给的保存方法包含所有DepartmentsLocations
过的数组。因此CakePHP的摧毁一切,并尝试重新创建它。
这是蛋糕一个常见的错误,因为它往往会拉太多的结果给你。
请务必通过只需要保存,或更好地只获取你需要的DATAS的数据。