mercredi 26 juillet 2017

Scope not applying on relations

I have a scope on a model that is being applied and working when

return Service::with(['locations' => function ($query) use ($latitude, $longitude, $radius){
        $query->closeTo($latitude, $longitude, $radius);
}])->get();

This pulls back the correct 9 results from the database

However, it doesn't work when the relationship is deeper, for example

return Service_type::with(['services' => function($query) use ($conditions, $service_ids){
    $query->where('published', 1)
  },
  'services.locations' => function($query) use($latitude, $longitude) {
    $query->closeTo($latitude, $longitude, 10);
  }
])->get();

This pulls back 12 results, which is all of the results, the 3 extra are over 10 miles away and shouldn't be included

The scope is just a Haversine formula for working out distances

public function scopeCloseTo($query, $latitude, $longitude, $radius = 25)
    {
      $haversine = "(3959 * acos(cos(radians($latitude))
                     * cos(radians(latitude))
                     * cos(radians(longitude)
                     - radians($longitude))
                     + sin(radians($latitude))
                     * sin(radians(latitude))))";
     return $query
        ->select(['id', 'ccg', 'ccg_code']) //pick the columns you want here.
        ->selectRaw("{$haversine} AS distance")
        ->whereRaw("{$haversine} < ?", [$radius]);
    }

What is strange is if I set the radius to 1 on the Service_type::with query, nothing is brought back, if it's 2, everything is brought back.

This doesn't happen with the same query on Service::with

Am I doing somethign wrong?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire