0

我正在使用此型号代码删除记录。

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

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

因此,当删除在子表中具有相关记录的记录时,它会引发异常,例如

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 

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

4

3 回答 3

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

如果您还在视图文件中使用 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'
        )
    )
);
于 2013-02-14T14:13:05.950 回答
3

我猜, $this->loadModel() 返回一个 CActiveRecord 对象...

首先,您需要确保您要删除的记录确实已加载。其次,在语句开头使用@ 确实不允许错误。然后如果 CActiveRecord->delete() 返回 false,则意味着该记录没有被删除:

public function actionDelete($id) {
    $record = $this->loadModel($id);
    if ($record !== null) {
        if (@$record->delete()) {
            // code when successfully deleted
        } else {
            // code when delete fails
        }
    } else {
        // optional code to handle "record isn't found" case
    }
}
于 2012-10-15T16:41:28.057 回答
2

您不能删除对外键有限制的行,将其更改为set to null,或no action根据您的要求

所以你的钥匙会在set to null删除和cascadeupdate

于 2012-10-15T15:25:55.567 回答