Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'having' with paginate on relationship's column in laravel 5

I need to grab the vehicles whose relation 'dealer' is having distance < 200

Vehicle::join('dealers', 'vehicles.dealer_id', '=', 'dealers.id')
     ->select(DB::raw("dealers.id, ( cos( radians(latitude) ) * cos( radians( longitude ) ) ) AS distance"))
     ->havingRaw('distance < 200');

I am trying to use havingRaw on the alias 'distance' from the relation (belongsTo) dealer. But failed with an error:

Column not found: 1054 Unknown column 'distance' in 'having clause'

UPDATE

The issue actually occurs when I add paginate function to the above query like this.

$vehicle = Vehicle::join('dealers', 'vehicles.dealer_id', '=', 'dealers.id')
 ->select(DB::raw("dealers.id, ( cos( radians(latitude) ) * cos( radians( longitude ) ) ) AS distance"))
 ->havingRaw('distance < 200');

$result = $vehicle->paginate(15);
like image 642
Mirza Vu Avatar asked Oct 22 '16 15:10

Mirza Vu


2 Answers

Answer Updated corresponding to updated question

The problem is with the query builder as all selects are discarded when doing an aggregate call (like count(*)). The make-do solution, for now, is to construct the paginator manually as:

$query = Vehicle::join('dealers', 'vehicles.dealer_id', '=', 'dealers.id')
             ->select(DB::raw("dealers.id, ( cos( radians(latitude) ) * cos( radians( longitude ) ) ) AS distance"))
             ->having('distance', '<', '200');

$perPage = 10;
$curPage = \Illuminate\Pagination\Paginator::resolveCurrentPage();

$itemQuery = clone $query;

$items = $itemQuery->forPage($curPage, $perPage)->get();

$totalResult = $query->addSelect(DB::raw('count(*) as count'))->get();
$totalItems = $totalResult->first()->count;

$vehicles = new \Illuminate\Pagination\LengthAwarePaginator($items->all(), $totalItems, $perPage);
like image 80
Amit Gupta Avatar answered Sep 28 '22 07:09

Amit Gupta


having and havingRaw doesn't have access to generated fields in the query see this example from laravel docs enter image description here

Your query will have to lookk like this

Vehicle::join('dealers', 'vehicles.dealer_id', '=', 'dealers.id')
            ->select(DB::raw("dealers.id, ( cos( radians(latitude) ) * cos( radians( longitude ) ) ) AS distance"))
            ->havingRaw('(cos(radians(latitude)) * cos(radians(longitude))) < 200');
like image 27
Kliment Avatar answered Sep 28 '22 08:09

Kliment