首页  >  文章  >  后端开发  >  如何修复由于 MySQL 严格模式导致 Laravel Eloquent 中的“SELECT 列表的表达式 #1 不在 GROUP BY 子句中”错误?

如何修复由于 MySQL 严格模式导致 Laravel Eloquent 中的“SELECT 列表的表达式 #1 不在 GROUP BY 子句中”错误?

Linda Hamilton
Linda Hamilton原创
2024-10-18 12:29:03554浏览

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:

<code class="php">'mysql' => [
    // Disable strict mode
    'strict' => false,
],</code>

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:

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

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.

以上是如何修复由于 MySQL 严格模式导致 Laravel Eloquent 中的“SELECT 列表的表达式 #1 不在 GROUP BY 子句中”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn