解決Laravel Eloquent 中MySQL 的「Expression #1 of SELECT List Not in GROUP BY」錯誤
Lara Eloquent」錯誤
Lara Eloquent>錯誤使用時出現「SELECT List 的表達式#1 不在GROUP BY 子句中”錯誤groupBy() 方法。當非聚合列包含在 SELECT 清單中,而對其他資料列執行聚合時,通常會發生這種情況。$products = Product::where('status', 1) ->where('stock', '>', 0) ->where('category_id', '=', $category_id) ->groupBy('store_id') ->orderBy('updated_at', 'desc') ->take(4) ->get();
考慮以下Laravel Eloquent 查詢:
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'myshop.products.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select * from products where status = 1 and stock > 0 and category_id = 5 group by store_id order by updated_at desc limit 4)
執行此查詢可能會導致以下錯誤:
要解決此問題,請在資料庫連線中停用MySQL 的嚴格模式設定。此模式強制執行更嚴格的 SQL 語法和列分組,這可能與正在執行的查詢發生衝突。'connections' => [ 'mysql' => [ // Behave like MySQL 5.6 'strict' => false, // Behave like MySQL 5.7 'strict' => true, ] ]
修改 config/database.php 檔案中的資料庫設定:
設定嚴格選項設定為 false 以停用 MySQL 連線中的嚴格模式。這應該可以解決「SELECT List 的表達式 #1 不在 GROUP BY 中」錯誤。 有關更高級的配置設置,請參閱 Matt Stauffer 的部落格文章。以上是如何修復 Laravel Eloquent 的「SELECT 清單的表達式 #1 不在 GROUP BY 中」MySQL 錯誤?的詳細內容。更多資訊請關注PHP中文網其他相關文章!