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);
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);
having
and havingRaw
doesn't have access to generated fields in the query
see this example from laravel docs
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With