我那裏有五個字段一個相對簡單的輸入模式:當使用saveAll時,CakePHP的beforeSave不保留新數據?
- ID
- 型(該項是什麼數據類型)
- 量(多少是任何類型)
- 單元(該類型的單位)
- 日期(時輸入此項的datettime)
- USER_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的結束和「白水」的使用我的所有更改會丟失和$this->data
回覆到它的原始狀態之間的某處。因此不會發生儲蓄。
這不起作用,至少使用行爲...:_( – elboletaire 2014-01-23 12:27:48