Answer the question
In order to leave comments, you need to log in
How to correctly add groupBy to the query?
Hello, please tell me, there are categories on the site, and categories have characteristics, for some categories it happens that some part of the characteristics is similar, and I need to remove these duplicates, that is, leave categories with only unique characteristics, and I would like to do this with a request to db and not in controller using php.
As a result, I make the following query to the database:
$categories = Category::whereIn('id',$request->input('categories'))->with(['characteristics' => function($query) {
$query->groupBy('id');
}])->get();
select `characteristics`.*, `category_characteristic`.`category_id` as `pivot_category_id`, `category_characteristic`.`characteristic_id` as `pivot_characteristic_id` from `characteristics` inner join `category_characteristic` on `characteristics`.`id` = `category_characteristic`.`characteristic_id` where `category_characteristic`.`category_id` in (51, 52) group by `id`
Ошибка в запросe (1055): Expression #5 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'rqt1mvsaw_js3ht.category_characteristic.category_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
$query->groupBy('id');
Answer the question
In order to leave comments, you need to log in
This is the correct base behavior for such a query. To avoid ambiguity, if grouping is used, then either you can use only fields from the grouping in the select, or use aggregate functions, or conjure with subqueries. In order for the main query to be valid, taking into account aggregation, and its results to be used to obtain the rest of the data using JOIN or WHERE IN
In your case, if you still want to use Eloquent, you need to define the minimum required data set and query only them. What do you need a list of id and titles?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question