1. 程式人生 > >Laravel : Syntax error or access violation: 1055 Error

Laravel : Syntax error or access violation: 1055 Error

public function uploads($count)
    {
        $items = \DB::table('article')
            ->select('pcode.name', \DB::raw('count(*) as upload_count'))
            ->leftJoin('pcode', 'article.organization_id', '=', 'pcode.id')
            ->where([
                ['pcode.type', '=', "organization_type"
], ['article.status', '=', 1] ]) ->groupBy('organization_id'); return $items->paginate($count); }

上面這樣一段程式碼, 測試伺服器很好, 上線後報錯了.
Syntax error or access violation: 1055 Error : MySQL : isn't in GROUP BY
云云

後來Google了一下說是sql_mode設定導致的問題, 修改 config/database.php

這個配置 strict => false

'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset'
=> 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, 'engine' => null, ],

然後試了一下 果然問題解決了 ,然後仔細查閱了一下原因:

查詢mysql 1055錯誤碼發現問題為在mysql的配置中如果設定了sql_mode包含
ONLY_FULL_GROUP_BY值得話,在進行查詢時需要將select的欄位都包含在group by 中。
即 select x,y from xxx group by x,y
否則就會報錯

總結:

laravel 5.3 是預設開啟 mysql嚴格模式的.
mysql在嚴格模式下, 並且開啟了ONLY_FULL_GROUP_BY的情況下,
group by 的欄位沒有出現在 select 的語句中會報錯.關閉了嚴格模式就不會報錯.