ApiController.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Distributor\Controllers;
  3. use App\Distributor\Repositories\DistProduct;
  4. use App\Distributor\Repositories\SitePages;
  5. use App\Distributor\Repositories\SitePagesTag;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Routing\Controller;
  8. class ApiController extends Controller
  9. {
  10. /**
  11. * 产品下接API,默认返回50个最新的产品
  12. */
  13. public function products(Request $request)
  14. {
  15. $q = $request->get('q');
  16. if ($q != null) {
  17. // 模糊搜索
  18. $obj = new DistProduct();
  19. return $obj->model()->where('title', 'like', "%$q%")->paginate(null, ['id', 'title as text']);
  20. } else {
  21. // 获取最新的50个
  22. $selectOptionsNew = DistProduct::selectOptionsNew();
  23. return $this->changeOptions($selectOptionsNew);
  24. }
  25. }
  26. public function pages(Request $request)
  27. {
  28. $q = $request->get('q');
  29. if ($q != null) {
  30. // 模糊搜索
  31. $obj = new SitePages();
  32. return $obj->model()->where('title', 'like', "%$q%")->paginate(null, ['id', 'title as text']);
  33. } else {
  34. // 获取最新的50个
  35. $selectOptionsNew = SitePages::selectOptionsNew();
  36. return $this->changeOptions($selectOptionsNew);
  37. }
  38. }
  39. public function tag(Request $request)
  40. {
  41. $q = $request->get('q');
  42. if ($q != null) {
  43. // 模糊搜索
  44. $obj = new SitePagesTag();
  45. return $obj->model()->where('name', 'like', "%$q%")->paginate(null, ['id', 'name as text']);
  46. } else {
  47. // 获取最新的50个
  48. $selectOptionsNew = SitePagesTag::selectOptionsNew();
  49. return $this->changeOptions($selectOptionsNew);
  50. }
  51. }
  52. /*
  53. * 把数据转换成select需要的格式
  54. */
  55. private function changeOptions($data) {
  56. // 初始化结果数组
  57. $result = [];
  58. // 遍历原始数据并转换格式
  59. foreach ($data as $id => $text) {
  60. $result[] = [
  61. 'id' => (int)$id, // 将字符串转换为整数
  62. 'text' => $text
  63. ];
  64. }
  65. return $result;
  66. }
  67. }