【问题标题】:How to use pagination in laravel 5 with Raw query如何在 laravel 5 中通过 Raw 查询使用分页
【发布时间】:2015-07-31 00:54:03
【问题描述】:

我有一个简单的问题,但没有找到我需要的。

我需要计算商店列表的 t2 地理编码点之间的距离。我还需要为 WebService 分页。

这可行,但结果中没有距离:

public function stores(){
    return Store::paginate(10);
}

结果是:

{
   total: 4661, 
   per_page: 10, 
   current_page: 6, 
   last_page: 467,
   next_page_url: "WS_URL/stores/?page=7",
   prev_page_url: "WS_URL/stores/?page=5", from: 51,
   to: 60, 
   data: [ { 
        id: "51", 
        name: "Sprouts",
        .
        .
        lng: "-118.359688", 
        lat: "33.808281", 
        country: "usa" 
        },
    .
    .
    .
    ]}

但我需要这段代码工作:

public function stores(){
    return DB::table('stores')
        ->selectRaw(' *, distance(lat, ?, lng, ?) as distance ')
        ->setBindings([ 41.123401,1.2409893])
        ->orderBy('distance')
        ->paginate($this->limit);
}

结果如下:

{total: 0,
    per_page: 10,
    current_page: 1,
    last_page: 0,
    next_page_url: null,
    prev_page_url: null,
    from: 1,
    to: 10,
    data: [{
        id: "3686",
        name: "Bon Area", 
        .
        .
        lng: "1.602016",
        lat: "41.266823",
        distance: "0.15091"
        },
    .
    .
    .
    ]
}

我需要next_page_urlprev_page_url

有什么想法吗?

【问题讨论】:

    标签: php laravel pagination laravel-5


    【解决方案1】:

    在 Eloquent 模型上使用 selectRaw 方法。

    Store::selectRaw('*, distance(lat, ?, lng, ?) as distance', [$lat, $lon])
        ->orderBy('distance')
        ->paginate(10);
    

    在这种情况下,Laravel 会向数据库询问行数(使用 select count(*) as aggregate from stores),这可以节省您的 RAM。

    【讨论】:

      【解决方案2】:

      好的,我有一个解决方案! 我不喜欢它,因为我必须将所有行加载到 RAM 中,然后使用手动分页器。

      public function stores($lat, $lon){
          $stores = DB::table('stores')
              ->selectRaw(' *, distance(lat, ?, lng, ?) as distance ')
              ->setBindings([$lat,$lon])
              ->orderBy('distance')
              ->get();
          $result_p = new Paginator($stores, $this->limit, Request::input('page'),['path' => Request::url() ]);
          return $result_p;
      }
      

      在此之后,我查看了更多信息,问题是 setBindings([$lat,$lon])

      最新最好的解决方案:

      public function stores($lat, $lon){
          return $stores = DB::table('stores')
              ->selectRaw(" *, distance(lat, {$lat}, lng, {$lon}) as distance ")
              ->orderBy('distance')
              ->paginate($this->limit);
      }
      

      【讨论】:

        猜你喜欢
        • 2018-01-31
        • 1970-01-01
        • 2017-07-03
        • 2015-03-14
        • 2014-05-18
        • 2023-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多