laravel8資料庫操作之group by踩坑

baitiao發表於2021-01-19

laravel8資料庫操作之group by踩坑

$product = \DB::table(“product”)->selectRaw(“name,create_time”)
->groupBy(“create_time”)
->get();

報錯:

SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘db.t_product.name’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select name,create_time from t_product group by create_time)

解決:
/config/database.php 檔案裡的strict引數修改為false即可

‘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’ => ‘t_’,
‘prefix_indexes’ => true,
‘strict’ => true,//這裡修改為false
‘engine’ => null,
‘options’ => extension_loaded(‘pdo_mysql’) ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env(‘MYSQL_ATTR_SSL_CA’),
]) : [],
]

我用的mysql8,網上搜了一下說是mysql8的問題,然後修改了sql_mode的內容。但是laravel專案執行這段程式碼依然報錯,於是我就裝了一個mysql5.7,發現問題依然存在。
於是百度 laravel group報錯 問題解決
結帖

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章