| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- <?php
- namespace App\Services;
- use App\City;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Support\Str;
- use App\Traits\ServiceAppAop;
- class CityService
- {
- use ServiceAppAop;
- protected $modelClass=City::class;
- public static $cities = ['汕头','汕尾'];
- /*
- * array | string $column
- * 默认一些select字段,可传递string 或 array来指定select字段
- */
- public function getSelection($column = ['id','name']){
- if (!is_array($column)) {
- $column = [$column];
- }
- return City::query()->select($column)->get();
- }
- public function find($id){
- return City::query()->find($id);
- }
- public function findByName($name)
- {
- $city = City::query()->where('name',$name)->first();
- if(isset($city))return $city;
- if(!$name)return null;
- foreach (CityService::$cities as $city) {
- if(strstr($city,$name) != null || strstr($name,$city)){
- return City::query()->where('name','like',$city.'%')->first();
- }
- }
- if(str_ends_with($name,'自治州')){
- $city_name = Str::before($name,'自治州');
- return City::query()->where('name','like',$city_name.'%')->first();
- }
- if(str_ends_with($name,'市')){
- $city_name = Str::before($name,'市');
- return City::query()->where('name','like',$city_name.'%')->first();
- }
- return null;
- }
- /**
- * 根据名称获取城市
- *
- * @param string|null $name
- *
- * @return Model|null
- */
- public function getCity(?string $name = null):?Model
- {
- if (!$name)return null;
- $cityName = mb_substr($name,0,3);
- return app(CacheService::class)->getOrExecute("city_".$cityName,function ()use($cityName){
- return City::query()->where("name","like",$cityName."%")->first();
- },86400);
- }
- }
|