选择多个字段的Laravel groupBy



我可以选择country和groupBy结果如下,并使用别名total:

Data::select('country', DB::raw('count(*) as total'))
->groupBy('country')
->get();

上面的代码运行良好。这里我只能选择country字段,但是我需要同时选择name,positions字段,我怎么能在这里选择多个字段?

你必须使用下面的设置和更改代码。

  1. 打开config/database.php
  2. 查找mysql连接设置中的strict
  3. 设置为false

使用下面类似

的代码
ModelName::groupBy('country')
->selectRaw('count(*) as total, country, name, positions')
->get()

首先,您需要指定得到的错误/异常但是您可以通过

添加额外的列
DB::table('table_name')->select([DB::raw('count(*) as total'), 'name', 'positions', 'country'])
->groupBy('country')
->get());

你也可能得到一个访问冲突异常,要求你改变sql_mode

最新更新