如何处理删除上的完整性约束违规行为



我有行,因为它引用了其他表,而某些行不能被删除,而另一个可以删除。

我想要的是删除行,可以删除并留下无法删除的其他行

到目前为止,我的代码是

$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

当记录删除并显示失败时,如果无法删除记录,而不是显示成功。

我的代码怎么了?

预先感谢。

这个将更好

使用yii db IntegrityException;

使用yii web notfoundhtpexception;

  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 yiiwebHttpException(500,"YOUR MESSAGE.", 405);

      }catch (Exception $e) {
          $transaction->rollBack();
          throw new yiiwebHttpException(500,"YOUR MESSAGE", 405);

    }
}
foreach($tkota as $kota){
     try {
        if($kota->delete()){
           echo "del success<br/>";
        }
     } catch (Exception $e) {
        echo "fail ".$kota['api_id']."<br/>";
     }
}

最新更新