request = $request; } /** * 使用名称查找企业 * * @return void */ public function companies(CompanyRepository $companyRepository) { return res($this->search($companyRepository), '', 201); } /** * 使用名称查找套餐 * * @return void */ public function packages(PackageRepository $packageRepository) { $type = $this->request->ids('type'); return res($this->search($packageRepository->whereIn('type', $type), ['name', 'carrier_operator']), '', 201); } /** * 统一搜索归并 * * @param [type] $repository * @param string $field * @param integer $limit * @param string $primaryKey * @return void */ protected function search($repository, $field = 'name', $primaryKey = 'id') { $search = $this->request->get('search'); $limit = $this->request->get('limit', 0); $field = array_wrap($field); $field = array_merge([$primaryKey, 'status'], $field); $results = $repository->select($field)->get(); if ($search) { $results = $results->filter(function ($item) use ($search, $field) { $result = true; if (strpos($item[$field], $search) === false) { $result = false; } if (strpos(pinyin_abbr($item[$field]), $search) === false) { $result = false; } if (strpos(implode('', pinyin($item[$field])), $search) === false) { $result = false; } return $result; }); } $sorted = $results->sortBy($field)->values()->all(); if ($limit) { return array_slice($sorted, 0, $limit); } return $sorted; } }