我在CakePHP中遇到了我的HABTM關係問題。CakePHP HABTM:編輯一個項目會導致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
的名字,都被鏈接到Location
該DepartmentsLocation
S的空網址重新創建。由於模型指定唯一性爲真,這也會導致所有較新的行覆蓋舊行,這實質上會破壞所有的URL。
我想知道兩件事: 我可以阻止它嗎?如果是這樣,怎麼樣?
而且,在一個技術性較低,更wh note的筆記上:爲什麼會發生這種情況?在我看來,通過Cake編輯字段應該會造成很多麻煩,當我可以輕鬆地通過phpMyAdmin,在那裏編輯Location
名稱,並獲得我期望的結果。爲什麼CakePHP只在一行中編輯字段時觸及HABTM數據?它甚至不是外鍵!
注'「獨特」 =>「keepExisting''在各國無法重新創建現有HABTM項目HABTM定義選項。這是很好的,如果你真的想要* *保存新的關係,但又不想失去更多的數據。 – Yogu 2013-05-05 18:52:17