A.* isn't in GROUP BY with left join on laravel query builder

◇◆丶佛笑我妖孽 提交于 2019-11-28 14:24:16

To fix this issue you need to specify required columns in select list and group by clause

$search_alls=DB::table('a16s as A')
                ->select('A.id','A.name')
                ->addSelect(DB::raw('SUM(CASE WHEN B.approve = 1 ELSE 0 END) as Yshow'))
                ->leftjoin('a16s_likes as B', function($join) {
                    $join->on('A.id', '=', 'B.p_id');
                })
                ->groupBy('A.id')
                ->groupBy('A.name');
    ->get();

As per newer release mysql 5.7 does not permit queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are not named in the GROUP BY clause

12.19.3 MySQL Handling of GROUP BY


As per docs

MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them. (Before 5.7.5, MySQL does not detect functional dependency and ONLY_FULL_GROUP_BY is not enabled by default

use select('A.*') to select all columns

 $search_alls=
    DB::table('a16s as A') 
    ->select('A.*')
    ->addSelect(DB::raw('SUM(CASE WHEN B.approve = 1 ELSE 0 END) as Yshow'))
    ->leftjoin('a16s_likes as B', function($join) {
        $join->on('A.id', '=', 'B.p_id');
        })
    ->groupBy('A.id')
    ->get();

You have to turn off sctrict mode in Laravel application.

go to config/database.php

under the MySQL set

strict => false

and it will start working.

Hope this helps.

I saw your issue in detail. and I've faced same issue. in database.php, there are below setting

'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => false,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

When I set strict property as false, it was working, and i've solved issue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!