How to use pagination in laravel 5 with Raw query

后端 未结 2 384
温柔的废话
温柔的废话 2020-12-11 04:46

I have a simple question and I didn´t find what I need.

I need to calculate the distance between t2 geocode points for a list of Stores. I also need it to be paginat

相关标签:
2条回答
  • 2020-12-11 05:20

    Ok, I got a solution! I don´t like it because I must to load all the rows in RAM and then use the manual paginator.

    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;
    }
    

    After this I was looking more inforamtion and the problem is setBindings([$lat,$lon])

    The latest and Good solution:

    public function stores($lat, $lon){
        return $stores = DB::table('stores')
            ->selectRaw(" *, distance(lat, {$lat}, lng, {$lon}) as distance ")
            ->orderBy('distance')
            ->paginate($this->limit);
    }
    
    0 讨论(0)
  • 2020-12-11 05:21

    Use the selectRaw method on the Eloquent model.

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

    In that case Laravel asks the database for the amount of rows (using select count(*) as aggregate from stores) which saves your RAM.

    0 讨论(0)
提交回复
热议问题