我在 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;
}
}
?>
控制器完全无趣。
问题:
如果我编辑 a 的名称,则链接到该名称的Location
所有DepartmentsLocation
s 都将Location
使用空 URL 重新创建。由于模型指定 unique 为真,这也会导致所有较新的行覆盖较旧的行,这实质上会破坏所有 URL。
我想知道两件事:我可以停止吗?如果是这样,怎么做?
而且,在一个不太技术和更多抱怨的情况下:为什么会发生这种情况?对我来说,通过 Cake 编辑字段会引起这么多麻烦,这对我来说似乎很奇怪,因为我可以轻松地通过 phpMyAdmin,在Location
那里编辑名称,并得到我期望的结果。当我只是在一行中编辑一个字段时,为什么 CakePHP 会触摸 HABTM 数据?它甚至不是外键!