doushenxu7294 2017-03-04 00:39
浏览 61

Laravel Eloquent - 胡萝卜素配方和分页

Code Review

I have created a topic on Code Review branch.

Question

I'm using haversine formula to count distance from selected post-code to desired destination.

App\Models\Business.php

public function scopeDistance($query, $latitude, $longitude, $radius)
{
    $query->getQuery()->orders = [];
    return $query->select('*')
                 ->selectRaw("( 3959 * acos( cos( radians($latitude) ) * cos( radians( latitude ) )  * cos( radians( longitude ) - radians($longitude) ) + sin( radians($latitude) ) * sin(radians(latitude)) ) ) AS distance")
                 ->having('distance', '<=', $radius)
                 ->orderBy('distance');
}

Everything seems pretty ok, except when i use paginate() method instead of get()

I have been looking for solution, there are lots of topics describing this problem, but seems that people didn't come up with good solution for it.

Some solutions in my case caused incorrect values. Maybe i did something wrong - not sure...

However i came up with this solution and i would like to hear any feedback if it's ok in terms of performance and memory usage.

function custom_paginator($builder, $per_page)
{
    $path = current_route();
    $current_page = \Illuminate\Pagination\Paginator::resolveCurrentPage();

    if ( ! isset($builder->getQuery()->columns[1])) $count = $builder->count();
    else
    {
        $query = clone $builder->getQuery();
        $query->columns = [ $query->columns[1] ];
        $query->orders = null;
        $count = array_get(\DB::select("select count(*) as count from ({$query->toSql()}) as haversine", $query->getBindings()), 0)->count;
    }

    return new \Illuminate\Pagination\LengthAwarePaginator(
        $builder->forPage($current_page, $per_page)->get(),
        $count, $per_page, null, compact('path')
    );
}

I haven't got any more ideas how to improve it, at least it works and i dont need to call something like

count = count($results = $builder->get());
$items = $results->forPage($curPage, $perPage);

feedback really appreciated.

  • 写回答

1条回答 默认 最新

  • dsc71976 2017-03-04 01:22
    关注

    Did you really need to create a custom paginator?

    If not try to use default.

    The other thing I didn't like is the raw queries, you are using a laravel so take as much advantage as you can.

    You will need to show your controller action for more feedback.

    To be honest stackoverflow is not really the best place for this question, code review stack exchange would me more appropriate because you code already works and you just want to improve it

    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法