"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 Resolve SQL_MODE=ONLY_FULL_GROUP_BY Conflict in Laravel Eloquent?

How to Resolve SQL_MODE=ONLY_FULL_GROUP_BY Conflict in Laravel Eloquent?

Published on 2024-11-04
Browse:872

How to Resolve SQL_MODE=ONLY_FULL_GROUP_BY Conflict in Laravel Eloquent?

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();
Release Statement This article is reprinted at: 1729224796 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