yii2 model getErrors method to obtain errors
Model gets the wrong way
public static function getModelError($model) {
$errors = $model->getErrors(); //得到所有的错误信息
if(!is_array($errors)) return '';
$firstError = array_shift($errors);
if(!is_array($firstError)) return '';
return array_shift($firstError);
}
getErrors () :
Return all attributes or errors of a single attribute, that is, return all errors that occurred in the verification.
$model = new User();
$model->name = $name;
$model->nick_name = $nick_name;
$model->phone = $phone;
$model->sex = $sex;
$model->isNewRecord = true; //此语句可省略
if(!$model->save()){
//保存不成功
throw new \RuntimeException('保存败.'.$model::getModelError($model));
}
getErrors ()
Array
(
[cid] => Array
(
[0] => Cid不能为空=> Array
(
[0] => Times不能为空
$model->getFirstErrors()
Returns the first error message for each attribute. The return is as follows:
Array
(
[cid] => Cid不能为空=> Times不能为空
$model->getFirstError('cid'); The return is as follows:
Cid cannot be empty.