mardi 18 juillet 2017

Returning scope data in a collection

Below is a function I have on a model which brings back a Service with the data from three relationships. The scope closeTo contains data relating to how far a location is from a service which I would also like returned, but it currently only uses it to figure out distances.

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

the $query->closeTo uses the function below, and I want to send the distance data back with the return from the first function.

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]);
    }

Whats the best wat to achieve this?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2vzbAq2
via IFTTT

Aucun commentaire:

Enregistrer un commentaire