php - How do I put complex order by code into the model? -
i need order database objects relevance. relevance this: rating / distance(lat0, lng0, lat, lng)
. way in controller:
mymodel::orderby('rating / func(:lat0, :lng0, lat, lng)', [$lat, $lng])
but first, there's rather going argument, since latitude appears twice in formula:
mymodel::orderby('rating / func(:lat0, :lng0, lat, lng)', [$lat, $lat, $lng])
second, doesn't sound have in controller @ all. there i'd do:
mymodel::orderbyrelevance($lat, $lng)
so, idea extract sql formula helper function sql_distance_to($lat_col_name, $lng_col_name)
. then, add 1 more helper: sql_distance_to_args($lat, $lng)
, returns [$lat, $lat, $lng]
. , use these 2 in model make last statement possible. say? how do that?
you can approach defining dynamic scope in model (see eloquent query scopes), keeping logic in model & re-usable throughout application:
class mymodel extends model { public function scoperelevance($query, $lat, $lng) { // relevancy calculation. // return query builder instance. return $query->where('...'); } }
and use as:
mymodel::relevance($lat, $lng)->get();
Comments
Post a Comment