我有一些行,其中一些行无法删除,因为它引用了其他表,而其他行可以删除。
我想要的是删除可以删除的行并保留其他不能删除的行
到目前为止我的代码是
$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
而不是在删除记录时显示成功,在无法删除记录时显示失败。
我的代码有什么问题吗?
提前致谢。
最佳答案
这个会更好
use yii\db\IntegrityException;
use 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);
}
}
关于yii2 - 如何处理删除时违反完整性约束的情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41357609/