Search.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace addons\wwh\controller;
  3. use think\Db;
  4. use think\Request;
  5. class Search extends Base
  6. {
  7. public function index()
  8. {
  9. // 获取请求参数
  10. $keywords = input('keywords', '');
  11. $type = input('type', '');
  12. // 分配基础变量到模板
  13. $this->assign([
  14. 'keywords' => $keywords,
  15. 'type' => $type
  16. ]);
  17. // 类型映射
  18. $typeArr = [
  19. 1 => 'product',
  20. 2 => 'cases',
  21. 3 => 'news'
  22. ];
  23. $currentType = $typeArr[$type] ?? '';
  24. // 获取分页列表数据
  25. $query = Db::name('wwh_archives')
  26. ->where([
  27. 'status' => '1',
  28. 'lang' => $this->lang
  29. ]);
  30. if ($currentType) {
  31. $query->where('type', $currentType);
  32. }
  33. if ($keywords) {
  34. $query->where('title', 'like', "%{$keywords}%");
  35. }
  36. $list = $query->paginate(9, false, ['query' => request()->param()]);
  37. // 获取各类别统计数
  38. $countQuery = Db::name('wwh_archives')
  39. ->where([
  40. 'status' => '1',
  41. 'lang' => $this->lang
  42. ]);
  43. if ($keywords) {
  44. $countQuery->where('title', 'like', "%{$keywords}%");
  45. }
  46. $result = $countQuery
  47. ->field(['type', 'COUNT(*) AS total'])
  48. ->group('type')
  49. ->select();
  50. // 初始化统计数组
  51. $countData = array_fill_keys(['product', 'cases', 'news'], 0);
  52. // 填充统计结果
  53. foreach ($result as $item) {
  54. if (isset($countData[$item['type']])) {
  55. $countData[$item['type']] = $item['total'];
  56. }
  57. }
  58. // 确定当前导航栏目
  59. $navCur = ['classify' => $currentType ?: 'none'];
  60. // 分配变量到模板
  61. $this->assign([
  62. 'list' => $list,
  63. 'searchPage' => $list->render(),
  64. 'productCount' => $countData['product'],
  65. 'casesCount' => $countData['cases'],
  66. 'newsCount' => $countData['news'],
  67. 'navCur' => $navCur
  68. ]);
  69. // AJAX请求返回JSON
  70. if (Request::instance()->isAjax()) {
  71. return json([
  72. 'list' => $list,
  73. 'searchPage' => $list->render()
  74. ]);
  75. }
  76. return $this->view->fetch('/search');
  77. }
  78. }