php - SELECT 列表不在 GROUP BY 子句中并且包含非聚合列 'explore.ratings.id'

标签 php mysql laravel laravel-5 laravel-5.6

我要做的是选择行程,然后按费率对它们进行分组。

note: ratings is a polymorphic relationship

假设我们有 2 个模型:

trips
  id => int
  price => float
  city_id => uint
........

ratings:
  id => int
  ratable_id => int
  ratable_type=> varchar
  rate => small-int
......

我是怎么做的:

\App\Models\Trip::where('price','>=','100')->with(['ratings' => function ($query) {
        $query->groupBy('ratings.rate');
    }])->get();

哎呀!:

"SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'explore.ratings.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select * from ratings where ratings.ratable_id in (1, 2) and ratings.ratable_type = App\Models\Trip group by ratings.rate)

最佳答案

使用不同的方法:

$grouped = [];
$trips = \App\Models\Trip::where('price', '>=', '100')->with('ratings')->get();
foreach($trips as $trip) {
    foreach($trip->ratings as $rating) {
        $grouped[$rating->rate][] = $trip;
    }
}

或者使用 JOIN:

$trips = \App\Models\Trip::select('trips.*', 'ratings.rate')
    ->join('ratings', 'ratings.ratable_id', 'trips.id')
    ->where('ratings.ratable_type', 'App\Models\Trip')
    ->where('trips.price', '>=', '100')
    ->get();
$grouped = $trips->groupBy('rate');

关于php - SELECT 列表不在 GROUP BY 子句中并且包含非聚合列 'explore.ratings.id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51075541/

相关文章:

php - 如何在没有 SSH 的情况下在 GoDaddy 共享主机中托管 Laravel 5.2?

php - 如何在 Laravel Blade 中创建动态生成的下拉菜单

javascript - jQuery 奇怪的 JSON 行为

php - 调用未定义的方法 Illuminate\Database\Query\Builder::has_many()

php - 如何动态启用 SOAP、CURL、OPENSSL 扩展?

Php 登录表单不适用于 pdo 连接

php - 为什么 strtotime($lastmoment) 比 time() 大?

php - 如果未达到限制,我可以使用单个 MySQL 查询来选择不同的行,然后选择非不同的行吗?

php - 脚本显示进度 php

php - Laravel Eloquent 足球比赛日程中的多重关系