1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

LaravelでgroupBYして、エラーが起きた際の解決方法

Posted at

背景

Laravelでtableをselectする際に重複したカラムを絞り込みたいと思って、groupByを使った。 そしたら以下のようなエラーが
SQLSTATE[42000]: Syntax error or access violation: 1055 'laravel-shortcut.Tags.admin_id' isn't in GROUP BY

解決方法_1(推奨)

→SELECT部分にGROUP化するカラムをちゃんといれる

例えば、以下のようにする

Tag::select('id', 'name')
    ->groupBy('id')
    ->get();

以下のようにワイルドカードを使うとエラーが出る

Tag::select('Tags.*')
    ->groupBy('id')
    ->get();

解決方法_2

→config/database.phpを修正する

以下のように書く

config/database.php
            'strict' => true,
            //追記
            'modes'  => [
                // 'ONLY_FULL_GROUP_BY',
                'STRICT_TRANS_TABLES',
                'NO_ZERO_IN_DATE',
                'NO_ZERO_DATE',
                'ERROR_FOR_DIVISION_BY_ZERO',
                'NO_ENGINE_SUBSTITUTION',
            ],
      //追記

このように書くことで、SELECTで書いたものだけをGROUPBYさせようとする、やつを無効にできる

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?