我正在使用此型号代码删除记录。
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
是否有某种方式显示用户友好的错误消息。感谢
答案 0 :(得分: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'
)
)
);
答案 1 :(得分:2)
您无法删除对外键有限制的行,根据您的要求将其更改为set to null
或no action
所以你的密钥在删除时会set to null
和cascade
上的update
答案 2 :(得分:2)
我想,$ this-&gt; loadModel()返回一个CActiveRecord对象......
首先,您需要确保要删除的记录确实已加载。其次,在语句开头使用@会禁止错误。然后,如果CActiveRecord-&gt; 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
}
}