Home  >  Article  >  Backend Development  >  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?

Linda Hamilton
Linda HamiltonOriginal
2024-10-18 12:29:03549browse

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.

The above is the detailed content of How to Fix \"Expression #1 of SELECT list is not in GROUP BY clause\" Error in Laravel Eloquent Due to MySQL Strict Mode?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn