I'm doing a search query by distance and search term, but when using "Having" in eloquent, the standard pagination no longer works.
Here is my code:
$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();
This query works perfectly without the pagination, but when trying the standard
->paginat(10)
I get the following:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'distance' in 'having clause' (SQL: select count(*) as aggregate from
stores
havingdistance
< 26.1817)
I've done plenty of searching for this answer, but I'm not sure why the solutions I've found do not work for me.
I've already looked at: https://github.com/laravel/framework/issues/3105
and
How to use paginate() with a having() clause when column does not exist in table
Please give me some guidance if you have dealt with this issue in the past.
Edit:
Here is the code that I tried, but did not work properly for me.
$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);