"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Fix \"Expression #1 of SELECT list is not in GROUP BY clause\" Error in Laravel Eloquent Due to MySQL Strict Mode?

How to Fix \"Expression #1 of SELECT list is not in GROUP BY clause\" Error in Laravel Eloquent Due to MySQL Strict Mode?

Published on 2024-11-08
Browse:837

How to Fix \

Incompatibility with sql_mode=only_full_group_by in Laravel Eloquent

Encountering the error "Expression #1 of SELECT list is not in GROUP BY clause..." when executing an Eloquent query with grouping suggests an incompatibility with MySQL's sql_mode=only_full_group_by. To resolve this:

Disable MySQL Strict Mode

One solution is to disable the MySQL strict mode setting in your database connection configuration. In Laravel's .env file, add the following line:

DB_STRICT_MODE=false

Alternatively, you can configure the strict mode in your config/database.php file:

'mysql' => [
    // Disable strict mode
    'strict' => false,
],

Explanation

In MySQL 5.7 and later, the sql_mode=only_full_group_by mode requires that all columns in the SELECT list be either included in the GROUP BY clause or be aggregated functions. In the provided query:

$products = Product::where('status', 1)
            ->where('stock', '>', 0)
            ->where('category_id', '=', $category_id)
            ->groupBy('store_id')
            ->orderBy('updated_at', 'desc')
            ->take(4)
            ->get();

The column id (primary key) appears in the SELECT list but is not included in the GROUP BY clause. By disabling strict mode, MySQL will allow non-aggregated columns in the SELECT list that are not functionally dependent on the GROUP BY columns.

Release Statement This article is reprinted at: 1729224679 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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