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

前端 未结 5 478
耶瑟儿~
耶瑟儿~ 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 15:06

    Update

    If you use paginate() with your query laravel will try to execute the following SQL code to count the total number of possible matches:

    select count(*) as aggregate 
    from `vehicles` inner join `dealers` 
      on `vehicles`.`dealer_id` = `dealers`.`id`
    having distance < 200
    

    As you can see, there is no such column or alias distance in this query.

    Option 2 in my original answer will fix that issue too.

    Original answer

    That seams to be a MySQL-strict-mode issue. If you use laravel 5.3 strict mode is enabled per default. You have two options:

    Option 1: Disable strict mode for MySQL in config/database.php

    ...
    'mysql' => [
        ...
        'strict' => false,
        ...
    ],
    ...
    

    Option 2: Use a WHERE condtition

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

    Documentation:

    A MySQL extension to standard SQL permits references in the HAVING clause to aliased expressions in the select list. Enabling ONLY_FULL_GROUP_BY disables this extension, thus requiring the HAVING clause to be written using unaliased expressions.

    Server SQL Modes - ONLY_FULL_GROUP_BY

提交回复
热议问题