0

我正在按距离和搜索词进行搜索查询,但是在 eloquent 中使用“Having”时,标准分页不再有效。

这是我的代码:

    $haversine = '( 3959 * acos( cos( radians(?) ) * cos( radians( latitude ) ) * cos( radians( longitude ) - radians(?) ) + sin( radians(?) ) * sin( radians( latitude ) ) ) )';
    $stores = Store::select(
        DB::raw("*, $haversine AS distance"))
        ->having("distance", "<", $input['distance'])
        ->orderBy("distance")
        ->setBindings(array(
            $latitude,
            $longitude,
            $latitude
        ))
        ->with(array(
            'offers' => function($query) {
                if(Input::has('term')) {
                    $query->whereHas('product', function ($product_query) {
                        $product_query->where(function($term_query) {
                            $fields = array('name', 'description','model_number');
                            foreach($fields as $field) {
                                $term_query->orWhere($field, 'LIKE', '%' . Input::get('term') . '%');
                            }
                            $term_query->orWhereHas('brand', function($brand_query) {
                                $brand_query->where('name', 'LIKE', '%' . Input::get('term') . '%');
                            });
                        });
                    });
                }
                $query->orderBy('price', 'ASC');
            })
        )
        ->get();

此查询在没有分页的情况下完美运行,但在尝试标准时, ->paginat(10)我得到以下信息:

SQLSTATE [42S22]:未找到列:1054“有子句”中的未知列“距离”(SQL:选择计数(*)作为stores具有distance< 26.1817 的聚合)

我已经为这个答案做了很多搜索,但我不确定为什么我找到的解决方案对我不起作用。

我已经看过了: https ://github.com/laravel/framework/issues/3105

当表中不存在列时如何将 paginate() 与 having() 子句一起使用

如果您过去曾处理过此问题,请给我一些指导。

编辑:

这是我尝试过的代码,但对我来说不能正常工作。

$current_page = Paginator::getCurrentPage();
    $paginated_query = clone $stores;
    $paginated_query->addSelect('stores.*');

    $items  = $paginated_query->forPage($current_page, 10)->get();
    $totalResult = $stores->addSelect(DB::raw('count(*) as count'))->get();
    $totalItems = $totalResult[0]->count;

    $stores = Paginator::make($items->all(), $totalItems, 10);
4

1 回答 1

0

我在雄辩中使用“有”子句进行分页时遇到了同样的问题。

这对我有用:

不要在“have”子句中使用列的别名,而是使用实际计算。

代替:

$model->select(DB::raw("*, $haversine AS distance"))->having("distance", "<", $input['distance']);

尝试这个:

$model->select("*")->having(DB:raw($haversine), "<", $input['distance']);
于 2015-11-10T22:06:51.703 回答