我有行,有些行无法删除,因为它引用了其他表,另一行可以删除。
我想要的是删除可以删除的行并留下其他无法删除的行
到目前为止,我的代码是
$tkota = TbKota::find()->all();
foreach($tkota as $kota){
if($kota->delete()){
echo "del success<br/>";
}else{
echo "fail ".$kota['api_id']."<br/>";
}
}
我上面的代码产生了这个错误
SQLSTATE[23503]: Foreign key violation: 7 ERROR: update or delete on table "tb_kota" violates foreign key constraint "fk_tb_produ_reference_tb_kota" on table "tb_produk_ekspedisi_by_vendor"
DETAIL: Key (kota_id)=(1771) is still referenced from table "tb_produk_ekspedisi_by_vendor".
The SQL being executed was: DELETE FROM "tb_kota" WHERE "kota_id"=1771
而不是在删除记录时显示成功,如果记录无法删除则显示失败。
我的代码出了什么问题?
提前感谢。
答案 0 :(得分:2)
这个会更好
使用yii \ db \ IntegrityException;
使用yii \ web \ NotFoundHttpException;
foreach($tkota as $kota){
$connection = \Yii::$app->db;
$transaction = $connection->beginTransaction();
try {
$kota->delete();
$transaction->commit();
return $this->redirect(['user/view', 'id' => $model->id]);
}catch (IntegrityException $e) {
$transaction->rollBack();
throw new \yii\web\HttpException(500,"YOUR MESSAGE.", 405);
}catch (\Exception $e) {
$transaction->rollBack();
throw new \yii\web\HttpException(500,"YOUR MESSAGE", 405);
}
}
答案 1 :(得分:1)
foreach($tkota as $kota){
try {
if($kota->delete()){
echo "del success<br/>";
}
} catch (\Exception $e) {
echo "fail ".$kota['api_id']."<br/>";
}
}