Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

php - How to use pagination in laravel 5 with Raw query

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 paginated for a WebService.

This works, but there is no distance in the result:

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

And the result is:

{
   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" 
        },
    .
    .
    .
    ]}

But I need this code working:

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

And this is the result:

{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"
        },
    .
    .
    .
    ]
}

I need the next_page_url and prev_page_url

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...