【问题标题】:Laravel Eloquent with() location searchLaravel Eloquent with() 位置搜索
【发布时间】:2020-08-13 15:02:50
【问题描述】:

我正在尝试返回一个教师类型的用户列表,这些用户具有关联的教师个人资料、关联的班级和位置,并且在邮政编码 15 英里范围内。

如果没有该模型和用户的记录,它似乎会返回每个 obj 值为 null 的类型的每个用户,它会正确地添加到位置的距离,但没有按距离过滤,不知道为什么。

但我想要的只是具有教师资料(教师模型)和 15 英里范围内位置的用户。

我的模型中的函数

 public function searchLocationsByDistance($query, $lat, $lng, $max_distance = 15){
    $query->getQuery()->locations = [];
    return $query->select('*')
                 ->selectRaw("( 3959 * acos( cos( radians($lat) ) * cos( radians( lat ) )  * cos( radians( lng ) - radians($lng) ) + sin( radians($lat) ) * sin(radians(lat)) ) ) AS distance")
                 ->having('distance', '<=', $max_distance)
                 ->orderBy('distance');

}

我的控制器中的函数

  public function search(Request $request){

$input = $request->all();
//Just google api search this populates fine.
$location =  $this->geolocatePostcode( $input['postal_code'] ); 

$instructors=\App\User::with(['teacher', 'teacher.class','teacher.location' => function ($query) 
use($location) {
    $locations = new Location;
    $locations->searchLocationsByDistance($query,$location->lat,$location->lng);
    }])
    //->where('type', '==', 'instructor')
    ->get();

   // var_dump($instructors);
    return response()->json($instructors->toArray());

}

任何人都可以建议我的查询有什么问题或指导我正确的方向。

【问题讨论】:

    标签: laravel laravel-5 eloquent geolocation


    【解决方案1】:

    在原始查询中是否正确替换了变量?有几种方法可以做到这一点;

    ->selectRaw("...query some '$lat' more query...")
    

    ->selectRaw("...query some {$lat} more query...")
    

    你也可以用另一种方式替换变量;

    ->selectRaw("...query some :lat more query...", ['lat' => $lat])
    

    【讨论】:

    • 它正确地返回了距离别名,所以人们会想象那个位至少在工作。只是没有过滤任何内容,所有用户,即使他们没有教师记录
    【解决方案2】:

    您编写的 User 查询将返回所有内容,因为该查询没有过滤器。我认为使用 Laravel 方法 whereHas() 会对您有所帮助。

    试一试,但你需要根据我的猜测进行必要的调整,但这应该会给你一个帮助的想法:

    $instructors=\App\User::whereHas(['teacher', function($query) use($location){
         $query->with(['class', 'location' => function($q) use($location){
             $locations = new Location;
             $locations->searchLocationsByDistance($q,$location->lat,$location->lng);
         }])->where('type', '==', 'instructor');
    }])
        ->get();
    

    另外 - 在查询中更新 Location 可能无法按预期工作并且看起来很复杂。您可能希望首先在该内部查询中使用 $query-&gt;with(['class', 'location']); 来提取过滤后的教师列表,然后对该 集合 使用搜索位置方法。测试两种方法,看看哪种方法最有效/效果最好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-07
      • 1970-01-01
      • 2017-04-01
      • 2013-05-27
      • 2020-07-09
      • 1970-01-01
      • 2017-03-21
      • 2018-09-08
      相关资源
      最近更新 更多