【问题标题】:query string with laravel使用 laravel 查询字符串
【发布时间】:2019-03-08 12:30:56
【问题描述】:

我在 Laravel 5.6 中遇到了查询字符串的问题

我有这两个实体,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,除了正确位置的注释外,我还返回位置= null 的注释。将在数据库中看到这些注释只有一个参数与传入查询字符串的参数一致。理论上它不应该退回它们,我不能以任何方式将它们取下。有人可以帮我吗?

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

【问题讨论】:

  • 请在您的问题中提供文本格式的代码而不是图像。
  • 您好@Francesco,欢迎来到SO,代码应粘贴在问题中,以便于阅读和快速响应

标签: php laravel api eloquent


【解决方案1】:
Node::with(['location' => function($query) use ($latitude, $longitude){
    $query->where('latitude', $latitude);
    $query->where('longitude', $longitude);
}])->get()

【讨论】:

    【解决方案2】:

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

    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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-15
      • 2016-12-08
      • 2018-05-09
      • 1970-01-01
      • 2022-03-30
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多