# model 模型
## 命名
## 驗證規則
按照約定的順序進行字段驗證,并且需要繼承父級。
1. 過濾空格
2. 必須的字段
3. 字段聲明(int)
4. 字段聲明(string)
5. 個性化驗證
6. 唯一驗證
>[info] 順序必須保持與數據庫字段一致。
>[info] 除了最后兩種驗證,其它驗證第一個參數必須使用數組。
>[info] 必須的字段只需保證最少字段即可,更多的請寫在表單模型中。
>[info] `filter`驗證需要注意,將會自動將沒有值的字段變為空字符串`''`。
>[info] 字段聲明必要時請聲明最小值,如:`int`類型。
>[info] 錯誤信息使用`{attribute}`代替,并在句末加上句號。
~~~
/**
* 驗證規則
*/
public function rules()
{
$rules = parent::rules();
$new = [
[['username', 'mobile'], 'filter', 'filter' => 'trim'],
[['dealer_id', 'username'], 'required'],
[['dealer_id', 'address_id', 'sex', 'birthday', 'oauth_source', 'last_at', 'status', 'created_at', 'updated_at'], 'integer', 'min' => 0],
[['username'], 'string', 'min' => 5, 'max' => 16],
[['auth_key'], 'string', 'max' => 32],
[['password_hash', 'password_reset_token'], 'string', 'max' => 255],
[['email', 'real_name'], 'string', 'max' => 64],
[['mobile', 'last_ip'], 'string', 'max' => 16],
[['avatar', 'oauth_openid'], 'string', 'max' => 128],
['username', 'match', 'pattern' => '/^[(\x{4E00}-\x{9FA5})a-zA-Z]+[(\x{4E00}-\x{9FA5})a-zA-Z_\d]*$/u', 'message' => '{attribute}由字母、漢字、數字、下劃線組成,且不能以數字和下劃線開頭。'],
['email', 'email'],
['mobile', 'match', 'pattern' => '/^(((13[0-9]{1})|(14[0-9]{1})|(17[0]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-9]{1}))+\d{8})$/', 'message' => '請輸入有效的{attribute}。'],
['username', 'unique', 'targetClass' => Member::className(), 'message' => '此{attribute}已被使用。'],
['email', 'unique', 'targetClass' => Member::className(), 'message' => '此{attribute}已被使用。'],
['mobile', 'unique', 'targetClass' => Member::className(), 'message' => '此{attribute}已被使用。'],
];
// 合并數組
return ArrayHelper::merge($rules, $new);
}
~~~
## 自定義方法
### 優先前綴
優先寫出常用前綴的方法便于快速開發,具體為`get`、`set`、`del`。
>[info] `get`表示獲取數據,常用的有`getInfo`、`getList`。
>[info] `set`表示更新或添加數據,常用的有`setInfo`、`setList`。
>[info] `del`表示刪除數據,常用的有`delInfo`、`delList`。
~~~
public static function getInfo($id){ ... }
public static function getList($goodsId){ ... }
public static function setInfo(array $data){}
...
~~~