我正在尝试保存来自多个同名输入的大小数据。
问题是我无法保存数据。只有最后的价值"尺寸"正在保存在数据库中。
if ($this->EquipmentType->save($this->request->data['EquipmentType'], false)) {
$id = $this->EquipmentType->getLastInsertId();
$this->loadModel('EquipmentTypesSize');
$sizesArray = $this->request->data['EquipmentType']['size'];
foreach($sizesArray as $val){
$data[] = array('EquipmentTypesSize' => array('sizes' => $val));
}
$this->request->data['EquipmentTypesSize']['equipment_type_id'] = $id;
$this->EquipmentTypesSize->set($this->request->data);
$this->EquipmentTypesSize->save($this->request->data['EquipmentTypesSize']);
$this->Session->setFlash('Equipment type has been added successfully ', 'default', 'success');
$this->redirect(array('controller' => 'equipments', 'action' => 'listequipmenttypes', 'admin' => true));
}
我想将其保存为
equipment_type_id | size1
equipment_type_id | size2
equipment_type_id | size3
答案 0 :(得分:5)
有几个问题--Kay提到的对create
的呼吁就是其中之一。
首先,这是您的代码,但我已经在我看到明显问题的地方添加了评论(我很多都没有抓到所有问题)
<?php
if ($this->EquipmentType->save($this->request->data['EquipmentType'], false)) {
$id = $this->EquipmentType->getLastInsertId();
$this->loadModel('EquipmentTypesSize');
$sizesArray = $this->request->data['EquipmentType']['size'];
foreach($sizesArray as $val){
$data[] = array('EquipmentTypesSize' => array('sizes' => $val));
// WHERE IS THIS $data VARIABLE USED? It seems it's never used?
}
$this->request->data['EquipmentTypesSize']['equipment_type_id'] = $id;
$this->EquipmentTypesSize->set($this->request->data); // NO NEED TO CALL SET HERE - YOU ALREADY PASS DATA IN AS A PARAM TO SAVE
// YOU MUST CALL CREATE BEFORE ADDING A NEW RECORD
$this->EquipmentTypesSize->save($this->request->data['EquipmentTypesSize']);
// I DON'T THINK $this->request->data['EquipmentTypesSize'] HOLDS THE VALUE YOU THINK IT DOES AT THIS POINT
$this->Session->setFlash('Equipment type has been added successfully ', 'default', 'success');
$this->redirect(array('controller' => 'equipments', 'action' => 'listequipmenttypes', 'admin' => true));
}
现在,很难确切地说出你想要做什么,但这是我试图写出你想要的东西。如果它不起作用,它应该有希望让你走上正确的轨道。
if ($this->EquipmentType->save($this->request->data['EquipmentType'], false)) {
$id = $this->EquipmentType->getLastInsertId();
$this->loadModel('EquipmentTypesSize');
$sizesArray = $this->request->data['EquipmentType']['size'];
foreach($sizesArray as $val){
$this->EquipmentTypesSize->create();
$this->EquipmentTypesSize->save(array(
'sizes' => $val,
'equipment_type_id' => $id,
));
}
$this->Session->setFlash('Equipment type has been added successfully ', 'default', 'success');
$this->redirect(array('controller' => 'equipments', 'action' => 'listequipmenttypes', 'admin' => true));
}
最后,有两件事:
实际上,您应尽可能多地将这些逻辑推送到EquipmentType
模型中。因此,您可以在saveWithSizes
模型中创建一个包含大部分代码的EquipmentType
方法。
您应该查看Cake的saveAll
方法(http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array)。理想情况下,您可以设置表单数据,这样您就可以调用saveAll并让Cake自动处理它。对于你的情况,这可能是也可能不是。