Laravel own variable in scope

2019-07-22 01:54发布

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.

enter image description here

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条回答
Melony?
2楼-- · 2019-07-22 02:02

HAVING only works with GROUP BY

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

查看更多
登录 后发表回答