我要做的是选择行程,然后按费率对它们进行分组。
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
whereratings
.ratable_id
in (1, 2) andratings
.ratable_type
= App\Models\Trip group byratings
.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/