200, 'msg' => '获取成功', 'data' => [ 'userCounts' => $this->getUserCounts(), 'babyCounts' => $this->getBabyCounts() ] ]); } catch (DbException $e) { return json([ 'code' => 500, 'msg' => '获取失败:' . $e->getMessage() ]); } } /** * 统计宝贝数量 * @return array */ private function getBabyCounts(): array { try { // 总数 $total = AppsBabyhealthBabys::where('delete_time', null)->count(); // 男宝宝数 (sex = 1) $maleCount = AppsBabyhealthBabys::where('delete_time', null)->where('sex', 1)->count(); // 女宝宝数 (sex = 2) $femaleCount = AppsBabyhealthBabys::where('delete_time', null)->where('sex', 2)->count(); // 未知性别 (sex = 0) $unknownCount = AppsBabyhealthBabys::where('delete_time', null)->where('sex', 0)->count(); return [ 'total' => $total, 'male' => $maleCount, 'female' => $femaleCount, 'unknown' => $unknownCount ]; } catch (DbException $e) { // 返回空数组而不是抛出异常,让外层处理 error_log('统计宝贝数量失败: ' . $e->getMessage()); return [ 'total' => 0, 'male' => 0, 'female' => 0, 'unknown' => 0 ]; } } /** * 统计用户数量 * @return array */ private function getUserCounts(): array { try { // 总数 $total = AppsBabyhealthUsers::where('delete_time', null)->count(); // 父亲 (sex = 1) $fatherCount = AppsBabyhealthUsers::where('delete_time', null)->where('sex', 1)->count(); // 母亲 (sex = 2) $motherCount = AppsBabyhealthUsers::where('delete_time', null)->where('sex', 2)->count(); // 未知性别 (sex = 0) $unknownCount = AppsBabyhealthUsers::where('delete_time', null)->where('sex', 0)->count(); return [ 'total' => $total, 'father' => $fatherCount, 'mother' => $motherCount, 'unknown' => $unknownCount ]; } catch (DbException $e) { // 返回空数组而不是抛出异常,让外层处理 error_log('统计用户数量失败: ' . $e->getMessage()); return [ 'total' => 0, 'father' => 0, 'mother' => 0, 'unknown' => 0 ]; } } }