Yii2 common operations

Id get data after adding or modifying success

$insert_id = $UserModel->attributes['id'];

Native sql execution

$list = Yii::$app->db->createCommand('select * from user')->queryAll();

Sql get after execution

$sql = UserModel::find()->createCommand()->getRawSql();

Get the $model->saveerror message after

Model

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);
}   

Controller

throw new \RuntimeException('保存失败:'.$model::getModelError($model));

Develop common knowledge summary:

https://www.yiichina.com/topic/8274

understand more:

https://www.yiichina.com/doc/guide/2.0

https://www.yiiframework.com/doc/guide/2.0/zh-cn

Guess you like

Origin www.cnblogs.com/yulongcode/p/11628348.html