用laravel查询字符串

时间:2018-10-03 09:50:16

标签: php laravel api eloquent

我在Laravel 5.6中的查询字符串有问题

我有这两个实体ER模式: ER Schema

和相关模型: Note model Location model

我的问题是我必须在某个位置选择所有便笺作为查询字符串参数的纬度和经度。

查询字符串可以是:

homestead.test/api/notes?lat=45.5432&long=43.6543&max_distance=1.1

我尝试构建查询Here the NoteController code,但是存在问题:

实际上,输出显示了我的每一个音符。 这是postman output,除了正确位置的注释外,我还返回了location = null的注释。要在数据库中查看这些注释,只有一个参数与在查询字符串中传递的参数一致。从理论上讲,它不应该返回它们,我也不能以任何方式将它们取走。有人可以帮我吗?

我希望我已经足够清楚了,在此先感谢

2 个答案:

答案 0 :(得分:0)

Node::with(['location' => function($query) use ($latitude, $longitude){
    $query->where('latitude', $latitude);
    $query->where('longitude', $longitude);
}])->get()

答案 1 :(得分:0)

如果它可以帮助某人,我可以通过这种方式解决问题。

public function index(Request $request) {

    if($request->has('lat') &&
        $request->has('long')) {

        $lat1 = $request->query('lat');
        $long1 = $request->query('long');
        $max_distance = $request->query('max_distance');

        $notes = Note::All();

        foreach ($notes as $key => $value) {

            if($value->location != null) {
                $lat2 = $value->location->latitude;
                $long2 = $value->location->longitude;
                $distance = sqrt(pow($lat2-$lat1, 2) + pow($long2-$long1, 2));

                if($distance > $max_distance) {
                    $notes->forget($key);
                }    
            } else {
                $notes->forget($key);
            }

        }

        return $notes;
    }
    return Note::All();