YII中model層的一個小問題。。

來源:互聯網
上載者:User
下面是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 機制》

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.