首頁  >  文章  >  後端開發  >  yii實作model加入預設值的方法

yii實作model加入預設值的方法

高洛峰
高洛峰原創
2017-02-06 17:26:571269瀏覽

本文實例講述了yii實作model添加預設值的方法。分享給大家供大家參考,具體如下:

yii model 繼承自CActiveRecord

有些欄位可能不會出現在表單中,而需要在程式中加入。如訂單編號,時間戳,操作的user_id等等。

以下二種方法:

1、在rules()方法中設定:

public function rules()
{
  // NOTE: you should only define rules for those attributes that
  // will receive user inputs.
  return array(
    array('start, end', 'required'),
    array('user_id', 'numerical', 'integerOnly'=>true),
    array('timestamp','default','value'=>date('Y-m-d H:i:s')),
    // The following rule is used by search().
    // Please remove those attributes that should not be searched.
    array('id, start, end, user_id, timestamp', 'safe', 'on'=>'search'),
  );
}

2、在beforeSave()方法中設定:

function beforeSave()
{
  $this->user_id = Yii::app()->user->id;
  return true;
}

需要注意的是,beforeSave()方法需要return true,否則不會保存。

希望本文所述對大家以Yii架構為基礎的PHP程式設計有所幫助。

更多yii實作model加入預設值的方法相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn