我正在使用cakephp 1.3。保存我的HABTM关系时,我遇到了一个非常奇怪的问题。
阅读here,cakephp不会自动保存模型超过2级,我与hasMany和belongsTo建立了HABTM关系。
我有Application-> Child-> Membership-> Club关系。我将模型名称更改为cakephp cookbook中的示例,因为我的应用程序中的真实模型名称不是英文版。
class Child extends AppModel {
var $hasMany = array(
'Membership' => array(
'foreignKey' => 'child_id'
),
}
class Membership extends AppModel {
var $belongsTo = array(
'Child' => array(
'foreignKey' => 'child_id'
),
'Club' => array(
'foreignKey' => 'club_id')
);
}
class Club extends AppModel {
var $hasMany = array(
'Membership' => array(
'foreignKey' => 'club_id'
)
);
}
以下是Child控制器中正确保存我的孩子的方法 - >会员资格>俱乐部关系
function saveRelated() {
$childId= $this->Child->getLastInsertId(); // get the last inserted child
if(isset($this->data['Club'])) {
foreach ($this->data['Club'] as $key => $value) {
if ($this->checkIfEmpty($value)) { // if there was no club submitted in form, then unset array
unset($this->data['Club'][$key]);
unset($this->data['Membership'][$key]);
}
else {
$this->data['Membership'][$key]['child_id'] = $childId; // get the child_id from membership join table
$this->Child->Membership->Club->saveAll($this->data['Club'][$key]); // save the club
// from saved club, get club_id
$this->data['Membership'][$key]['club_id'] = $this->Child->Membership->Club->getLastInsertId();
}
}
$this->Child->Membership->saveAll($this->data['Membership']); // save Membership join-table with right ID-s
}
}
这是我的debug($this->data)
[Application] => Array
(
[id] => 361
[user_id] => 2
[created] => 2011-09-12 10:45:19
[modified] => 2011-09-12 10:45:19
[child_id] => 319
)
[Child] => Array
(
[child_id] => 319
[kkrid] => KAT-5684746
[name] => a33
[x] => 6400000
[y] => 640000
[coords] => X: 6400000, Y: 640000
[Membership] => Array
(
[0] => Array
(
[child_id] => 319
[modified] => 2011-09-12 10:45:21.14
[membership_id] => 75
[club_id] => 478
)
[1] => Array
(
[child_id] => 319
[modified] => 2011-09-12 10:45:21.14
[membership_id] => 76
[club_id] => 479
)
)
所以我在这里看不到Club阵列?它在哪里?当我想在应用程序中再次编辑表单时,没有俱乐部数据。
俱乐部数据必须在$this->data['Child']['Membership']['Club']
,但正如您所见,我的数据阵列中没有。
所有内容都正确保存在数据库中,而我的其他只有hasMany关系的表格保存正确且数据位于$this->data
但是为什么来自Club模型的数据来自$this->data
?如果必须如此,我的代码中没有任何错误,如何将俱乐部数据手动保存到$this->data
?