Resolving SQL_MODE=ONLY_FULL_GROUP_BY Conflict in Laravel Eloquent
When using Eloquent to perform a group-by query, you may encounter an error related to incompatible settings for sql_mode=only_full_group_by. This error can occur when non-aggregated columns are included in the SELECT list that are not part of the GROUP BY clause.
To solve this issue, you can disable the strict MySQL mode by setting the following in your database configuration file:
'connections' => [ 'mysql' => [ 'strict' => false, ] ]
By setting 'strict' to false, you are allowing MySQL to behave as if it were running in MySQL 5.6 mode, which does not enforce the strict grouping rules imposed by sql_mode=only_full_group_by.
Alternatively, you can modify your Eloquent query to ensure that all columns in the SELECT list are either aggregated or included in the GROUP BY clause. For example, you could use the 'raw' method to add the necessary aggregation:
$products = Product::where('status', 1) ->where('stock', '>', 0) ->where('category_id', '=', $category_id) ->groupBy('store_id') ->orderBy('updated_at', 'desc') ->selectRaw('*, COUNT(*) AS total_products') ->take(4) ->get();
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3