EndOrderAdminCommand.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. declare (strict_types = 1);
  3. namespace App\Command;
  4. use App\Model\Ad;
  5. use App\Model\Order;
  6. use App\Model\OrderAd;
  7. use Hyperf\Command\Annotation\Command; // 假设Order模型在App\Model命名空间下
  8. use Hyperf\Command\Command as HyperfCommand; // 假设OrderAd模型在App\Model命名空间下
  9. use Hyperf\DbConnection\Db;
  10. use Psr\Log\LoggerInterface;
  11. // 假设Ad模型在App\Model命名空间下
  12. #[Command]
  13. class EndOrderAdminCommand extends HyperfCommand
  14. {
  15. protected ?string $name = 'end:order-admin';
  16. protected $logger;
  17. public function __construct(LoggerInterface $logger)
  18. {
  19. parent::__construct();
  20. $this->logger = $logger;
  21. }
  22. public function configure()
  23. {
  24. parent::configure();
  25. $this->setDescription('结束订单并处理相关记录');
  26. }
  27. public function handle()
  28. {
  29. // 获取需要处理的订单ID列表
  30. // $currentTime = time();
  31. $currentTime = date('Y-m-d H:i:s');
  32. $orderIds = Order::where('status', 6)
  33. ->where('edtime', '<=', $currentTime)
  34. ->pluck('id')
  35. ->toArray();
  36. $this->info('需要处理的订单ID列表:' . implode(', ', $orderIds));
  37. foreach ($orderIds as $orderId) {
  38. $data = ['id' => $orderId];
  39. $this->processOrder($data);
  40. }
  41. }
  42. private function processOrder(array $data)
  43. {
  44. $order = Order::where('id', $data['id'])->first();
  45. if (empty($order)) {
  46. $this->logger->warning("没有找到订单ID: {$data['id']}");
  47. return;
  48. }
  49. Db::beginTransaction();
  50. try {
  51. $order->status = 7;
  52. $order->ad_status = 7;
  53. $order->save();
  54. // 获取 order_ad 表中的记录
  55. OrderAd::where('order_id', $data['id'])
  56. ->update(['status' => 7]);
  57. // 在ad表中删除相同pid的数据
  58. Ad::where('order_id', $data['id'])->delete();
  59. Db::commit();
  60. } catch (\Exception $e) {
  61. Db::rollBack();
  62. $this->logger->error("处理订单ID: {$data['id']} 时发生错误: " . $e->getMessage());
  63. }
  64. }
  65. }