Yii完整性约束异常处理与用户友好的消息

ali*_*sad 0 error-handling referential-integrity exception yii

我正在使用此模型代码删除记录.

public function actionDelete($id)
{
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if(!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
Run Code Online (Sandbox Code Playgroud)

包含此记录的表与其他表具有一对多关系,具有删除限制约束.

因此,当删除子表中具有相关记录的记录时,它会抛出异常

CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`bzuexamsystem`.`campus`, CONSTRAINT `fk_Campus_City` FOREIGN KEY (`CityID`) REFERENCES `city` (`CityID`) ON UPDATE CASCADE). The SQL statement executed was: DELETE FROM `city` WHERE `city`.`CityID`=1 
Run Code Online (Sandbox Code Playgroud)

是否有某种方式显示用户友好的错误消息.谢谢

小智 6

你需要捕捉异常.就像是

try{
    $this->loadModel($id)->delete();
    if(!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }catch (CDbException $e){
        if($e->getCode()===23000){
            //You can have nother error handling
            header("HTTP/1.0 400 Relation Restriction");
        }else{
            throw $e;
        }
    }
Run Code Online (Sandbox Code Playgroud)

如果您还在视图文件中使用CGrigView,则应将"ajaxUpdateError"函数传递给它.例:

$this->widget('zii.widgets.grid.CGridView',
  array(
    'id' => 'model-grid',
    'dataProvider' => $model->search(),
    'filter' => $model,
    'ajaxUpdateError' => <<<JS
      function(xhr, ts, et, err){
        if(xhr.statusText==="Relation Restriction"){
          $("#errorDiv").text("That model is used by something!");
        }
        else{
          alert(err);
        }
      }
    JS
    ,
    'columns' => 
        array(
            'model_id',
            'name'
        )
    )
);
Run Code Online (Sandbox Code Playgroud)