Home > Backend Development > PHP Tutorial > 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
Release: 2024-10-18 12:29:03
Original
674 people have browsed it

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
Copy after login

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

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

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template