TableOpsDao.php 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace app\common\dao\util;
  3. use think\facade\Db;
  4. class TableOpsDao
  5. {
  6. public function backupAndDeleteBatch(array $ops): void
  7. {
  8. foreach ($ops as [$table, $where]) {
  9. $this->backupAndDelete($table, $where);
  10. }
  11. }
  12. public function backupAndDelete(string $table, array $where): void
  13. {
  14. $rows = Db::name($table)->where($where)->select()->toArray();
  15. if ($rows) {
  16. Db::name('backup_' . $table)->insertAll($rows);
  17. Db::name($table)->where($where)->delete();
  18. }
  19. }
  20. public function restore(string $table, array $where): void
  21. {
  22. $backupTable = 'backup_' . $table;
  23. $rows = Db::name($backupTable)->where($where)->select()->toArray();
  24. if ($rows) {
  25. foreach ($rows as &$row) {
  26. if (isset($row['del_time'])) unset($row['del_time']);
  27. }
  28. unset($row);
  29. Db::name($table)->insertAll($rows);
  30. Db::name($backupTable)->where($where)->delete();
  31. }
  32. }
  33. public function restoreBatch(array $ops): void
  34. {
  35. foreach ($ops as [$table, $where]) {
  36. $this->restore($table, $where);
  37. }
  38. }
  39. }