2012-10-15 51 views
0

我正在使用此模型代碼來刪除記錄。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')); 
} 

包含此記錄的表與具有刪除限制約束的其他表具有一對多關係。

所以刪除已在子表相關記錄記錄時,它拋出像

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 

例外,有什麼方法來顯示用戶友好的錯誤消息。由於

+2

你的意思就像try/catch? – Asgaroth

+0

if($ this-> loadModel($ id) - > delete()){...} else {...} should be work –

回答

2

我猜測,$ this-> loadModel()返回一個CActiveRecord對象...

首先,您需要確保您要刪除的記錄真的被加載。其次,在語句開始時使用@會禁止錯誤。這時如果CActiveRecord->刪除()返回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 
    } 
} 
2

不能刪除有限制外鍵行,更改到set to null,或no action根據您的要求

所以你的關鍵將是對刪除 和cascadeset to nullupdate

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' 
     ) 
    ) 
); 
相關問題