setName('tools:db:table') ->setDescription('使用查询构建器操作表') ->addArgument('table', null, '表名') ->addOption('where', null, Option::VALUE_OPTIONAL, 'WHERE 条件') ->addOption('field', null, Option::VALUE_OPTIONAL, '查询字段,多个用逗号分隔') ->addOption('limit', null, Option::VALUE_OPTIONAL, '限制行数') ->addOption('order', null, Option::VALUE_OPTIONAL, '排序,如 "id DESC"') ->addOption('count', null, Option::VALUE_NONE, '只统计数量') ->addOption('connection', null, Option::VALUE_OPTIONAL, '指定数据库连接配置') ->addOption('help', 'h', Option::VALUE_NONE, '显示帮助信息'); } protected function execute($input, $output) { if ($input->getOption('help')) { $service = new ToolsDbServiceBase(); $service->showHelp('tools:db:table', $output); return; } $service = new ToolsDbServiceBase(); if (!$service->checkDebugMode($output)) { return; } $connection = $service->getDbConnection($input); $service->setConnection($connection); $tableName = $input->getArgument('table'); if (empty($tableName)) { $output->error('请提供表名'); return; } $fullTableName = $service->getFullTableName($tableName); $where = $input->getOption('where'); $field = $input->getOption('field'); $limit = $input->getOption('limit'); $order = $input->getOption('order'); $count = $input->getOption('count'); try { $startTime = microtime(true); $query = Db::connect($connection)->table($fullTableName); if ($field) { $query->field($field); } if ($where) { $query->whereRaw($where); } if ($order) { $query->orderRaw($order); } if ($count) { $result = $query->count(); $output->writeln(''); $output->writeln('表名:' . $fullTableName . ''); $output->writeln('记录数:' . $result); $output->writeln(''); } else { if ($limit && is_numeric($limit)) { $query->limit((int)$limit); } $result = $query->select()->toArray(); $endTime = microtime(true); $executionTime = round(($endTime - $startTime) * 1000, 2); $output->writeln(''); $output->writeln('表名:' . $fullTableName . ''); $service->formatTableOutput($result, $output); $output->writeln(''); $output->writeln('影响行数:' . count($result)); $output->writeln('执行时间:' . $executionTime . 'ms'); $output->writeln(''); } } catch (\Exception $e) { $output->error('查询失败:' . $e->getMessage()); return; } } }