【发布时间】:2011-06-14 19:56:53
【问题描述】:
我有一个相对简单的条目模型,只有五个字段:
- 身份证
- 类型(此条目是什么数据类型)
- 数量(无论是多少)
- unit(类型的单位)
- 日期(输入此条目的日期时间)
- user_id(进入用户的id
所以,没什么特别的。现在一个表单可以有多个条目(现有的和刚刚创建的新条目),表单通过 ajax 调用进行扩展。
当我提交表单时$this->data 看起来像这样:
Array
(
[Entry] => Array
(
[date] => 2011-01-07
[0] => Array
(
[id] => 1
[type] => Eat
[amount] => 1 Steak, one baked potatoe
[unit] => lunch
[time] => Array
(
[hour] => 13
[min] => 31
)
)
[1] => Array
(
[type] => weight
[amount] => 78.5
[unit] => KG
[time] => Array
(
[hour] => 22
[min] => 22
)
)
)
)
$this->data['Entry']['date'] 中的第一个条目是所有条目应使用的日期。由于还缺少 user_id,我在入口模型中创建了一个“beforeSave”函数。它看起来像这样:
function beforeSave() {
App::import('Component','Session');
$this->Session = new SessionComponent();
if (isset($this->data) && isset($this->data['Entry'])) {
$date = $this->data['Entry']['date'];
unset($this->data['Entry']['date']);
foreach ($this->data['Entry'] as $n => $entry) {
if (is_array($entry)) {
$this->data['Entry'][$n]['date'] = $date . ' ' . $entry['time']['hour'] . ':' . $entry['time']['min'] . ':00';
$this->data['Entry'][$n]['user_id'] = $this->Session->read('Auth.User.id');
}
}
debug($this->data);
}
return true;
}
我删除日期,将它与用户的时间条目一起添加,从而创建一个mysql日期时间条目并添加登录用户的user_id。直截了当,真的。结果数组(作为最后一个 debug() 的输出)如下所示:
Array
(
[Entry] => Array
(
[0] => Array
(
[id] => 1
[type] => Eat
[amount] => 1 Steak, 1 baked potatoe
[unit] => lunch
[time] => Array
(
[hour] => 09
[min] => 31
)
[date] => 2011-01-07 09:31:00
[user_id] => 2
)
[1] => Array
(
[type] => Weight
[amount] => 78.5
[unit] => KG
[time] => Array
(
[hour] => 22
[min] => 22
)
[date] => 2011-01-07 22:22:00
[user_id] => 2
)
)
)
所以它看起来和我想要的完全一样,而且应该很容易保存。但是当我使用$this->Entry->saveAll($this->data['Entry']) 保存所有条目时,它不仅不起作用,而且当我在saveAll 之后直接调试$this->data 时,它看起来就像在saveAll 函数之前一样——日期又回到了数组中,这些条目没有日期或 user_id 条目。
我可以看到调用了 beforeSave,我可以看到它更改了 $this->data,但是在 beforeSave 结束和使用“saveAll”之间的某个地方,我的所有更改都丢失了,$this->data 恢复到原来的状态.因此不会进行任何保存。
【问题讨论】: