ApiController.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. private function changeOptions($data) {
  53. // 初始化结果数组
  54. $result = [];
  55. // 遍历原始数据并转换格式
  56. foreach ($data as $id => $text) {
  57. $result[] = [
  58. 'id' => (int)$id, // 将字符串转换为整数
  59. 'text' => $text
  60. ];
  61. }
  62. return $result;
  63. }
  64. }