Laravel own variable in scope

谁说胖子不能爱 提交于 2019-12-11 00:34:31

问题


I'm using the haversine formula to calculate a distance, this is working fine.

But I would like to hide results where the distance is greater then the max_radius field on that result.

This is my database scheme.

This is the query I'm using. You can see I hard coded the distance (50)

public function scopeFitsDistance($query, $lat, $lng)
{
    return $query->select(\DB::raw("*,
                      ( 3959 * acos( cos( radians(?) ) *
                        cos( radians( lat ) )
                        * cos( radians( lng ) - radians(?)
                        ) + sin( radians(?) ) *
                        sin( radians( lat ) ) )
                      ) AS distance"))
            ->addBinding($lat, 'select')
            ->addBinding($lng, 'select')
            ->addBinding($lat, 'select')
            ->having('distance', '<', 50); <----------
}

But now I'm wondering how I can hide results where that distance < max_radius, which is a field inside the table.

The following returns no results

->having('distance', '<', 'max_radius');

Thank you!


回答1:


HAVING only works with GROUP BY

You can do a sub-select and then use a WHERE clause instead.



来源:https://stackoverflow.com/questions/42438137/laravel-own-variable-in-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!