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

前端 未结 5 473
耶瑟儿~
耶瑟儿~ 2020-12-10 14:22

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

Vehicle::join(\'dealers\', \'vehicles.dealer_id\', \'=\', \'dealers.id\')
          


        
5条回答
  •  一整个雨季
    2020-12-10 14:58

    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);
    

提交回复
热议问题