我制作了一个很大的形式,有许多协会hasMany / HABTM。一切都在创造(!)。当更新all也工作正常时,但在关联为hasMany的表中,数据不会更新或替换,而是刚插入。这会带来很多行的垃圾数据。如何让saveAll()在hasMany字段中执行更新/替换:
型号:
class MainModel extends AppModel {
var $hasAndBelongsToMany = array(
'HABTMModel1',
...
'HABTMModeln',
);
var $hasMany = array(
'Model1' => array(
'dependent' => true
),
...
'Modeln' => array(
'dependent' => true
),
);
}
其中一个有问题的hasMany模型如下:
class Model1 extends AppModel {
var $belongsTo = array(
'MainModel'
);
}
他的桌子有:
id <- Primary key, auto increment, int (11)
main_model_id <- Foreign_key int (11)
name <- text field, string
$ this-&gt;数据看起来像:
array(
[MainModel] => array(
'id' => 123
*** aditional data named identicaly to table fields (working great)***
),
[Model1] => array(
[0] => array(
[name] => Test1
),
[2] => array(
[name] => Test2
),
),
*** all other models ***
);
首次创建和更新后的Model1表结果:
id main_model_id name
--------------------------------------------------------------
11 306 Test1
12 306 Test2
13 306 Test1 (Thease are dublicates)
14 306 Test2 (Thease are dublicates)
如何更新/替换hasMany中的数据,而不是使用saveAll插入新值?
谢谢。
答案 0 :(得分:3)
在视图中,只需为所有Model1,Model2 ID
添加隐藏输入echo $form->create('MainModel'); echo $form->hidden('Model1.0.id'); // more stuffs... echo $form->end('Save');
您可能会为Model1指定'fields',Model2只能指定'name'。这就是$ this-&gt;数据看起来像这样的原因。所以只需添加'id'即可。
答案 1 :(得分:3)
所以我不是那么漂亮,而是工作:
// If edit, then delete data from hasMany tables based on main_model_id
if(isset($this->data['MainModel']['id']) && !empty($this->data['MainModel']['id'])) {
$conditions = array('main_model_id' => $this->data['MainModel']['id']);
// Delete Model1
$this->MainModel->Model1->deleteAll($conditions, false);
...
all other models
...
}
$this->MainModel->saveAll($this->data);
答案 2 :(得分:0)
您还需要为hasMany模型设置id
字段,例如
array(
[MainModel] => array(
[id] => 123
*** aditional data named identicaly to table fields (working great)*** ),
[Model1] => array(
[0] => array(
[id] => 1,
[name] => Test1
),
[2] => array(
[id] => 2
[name] => Test2
), ), *** all other models *** );