儲存您的資料(例項講述html5做網站)
阿新 • • 發佈:2019-02-15
CakePHP使儲蓄模型資料提前。資料可以儲存應該傳遞給模型的save()方法使用以下基本格式:
Array
(
[ModelName] => Array
(
[fieldname1] => 'value'
[fieldname2] => 'value'
)
)
大多數時候你甚至不需要擔心這種格式:CakePHP的FormHelper,模型在這種格式找到方法所有包資料。如果你使用的幫手,可用的資料也方便在$this->request->data 快速使用。
這裡有一個快速的例子使用CakePHP模型的控制器動作資料儲存在一個數據庫表:
public function edit($id) { // Has any form data been POSTed? if ($this->request->is('post')) { // If the form data can be validated and saved... if ($this->Recipe->save($this->request->data)) { // Set a session flash message and redirect. $this->Session->setFlash('Recipe Saved!'); return $this->redirect('/recipes'); } } // If no form data, find the recipe to be edited // and hand it to the view. $this->set('recipe', $this->Recipe->findById($id)); }
儲存時,資料傳遞給它的第一個引數是驗證使用CakePHP的驗證機制(有關更多資訊,請參見資料驗證章)。如果由於某種原因您的資料沒有儲存,一定要檢查,看看一些驗證規則被打破了。您可以通過輸出模型除錯這種情況::$ validationErrors:
if ($this->Recipe->save($this->request->data)) {
// handle the success.
}
debug($this->Recipe->validationErrors);
還有其他一些save-related模型中,你會發現有用的方法:
Model::set($one, $two = null)
Model::set()可用於設定一個或多個欄位的資料模型內部資料陣列。這是有用的在使用ActiveRecord模型與功能提供的模型:
$this->Post->read(null, 1); $this->Post->set('title', 'New title for the article'); $this->Post->save();
是如何使用的一個示例set()來更新單一領域,在一個ActiveRecord的方法。您還可以使用set()為新值分配給多個欄位:
$this->Post->read(null, 1);
$this->Post->set(array(
'title' => 'New title',
'published' => false
));
$this->Post->save();
上面會更新標題和釋出欄位和記錄儲存到資料庫中。
Model::clear()
該方法可用於重置模型狀態和清除任何未儲存的資料,驗證錯誤。