下面是controller層的代碼,用來儲存表單資料:
public function actionAdd(){ $categoryModel = new Category(); if(isset($_POST['Category'])){ $categoryModel->attributes = $_POST['Category']; if($categoryModel->save()){ $this->redirect(array('index')); } }
我查看了CActiveRecord中的save方法是這樣寫的:
public function save($runValidation=true,$attributes=null){ if(!$runValidation || $this->validate($attributes)) return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes); else return false;}
是我的理解的話應該是將$attribute傳進去,但實際上並沒有傳進去。而且假設不傳進去,也因該有:
if($attributes==null){$attributes=$this->attributes;}
之類的啊!怎麼連這個都沒有?
回複內容:
下面是controller層的代碼,用來儲存表單資料:
public function actionAdd(){ $categoryModel = new Category(); if(isset($_POST['Category'])){ $categoryModel->attributes = $_POST['Category']; if($categoryModel->save()){ $this->redirect(array('index')); } }
我查看了CActiveRecord中的save方法是這樣寫的:
public function save($runValidation=true,$attributes=null){ if(!$runValidation || $this->validate($attributes)) return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes); else return false;}
是我的理解的話應該是將$attribute傳進去,但實際上並沒有傳進去。而且假設不傳進去,也因該有:
if($attributes==null){$attributes=$this->attributes;}
之類的啊!怎麼連這個都沒有?
謝邀。
題主有沒有對 Category Model 使用 rule 規則,這涉及到了 Yii 中的 safe 機制,只有 Category 中的屬性是 safe 時,才能通過 $categoryModel->attributes 接收到資料。請參考:
《Understanding "Safe" Validation Rules》
總結了一篇博文,題主可以看下: 《源碼分析 Yii - save 機制》