Laravel语法GroupBy用于获取列到数组

62lalag4  于 2023-05-30  发布在  其他
关注(0)|答案(1)|浏览(169)

我有这样的数据库结构
消耗表

| ID | VOLTAGE | POWER | ENERGY |     CREATED_AT      |
| -- | ------- | ----- | ------ | ------------------- |
|  1 |     220 |  0.04 |      4 | 2023-05-03 13:04:05 |
|  2 |     210 |  0.03 |      5 | 2023-05-03 15:04:05 |
|  3 |     213 |  0.04 |      2 | 2023-05-06 02:04:05 |
|  4 |     221 |  0.05 |      4 | 2023-05-06 05:04:05 |

我有这样问题

return Consumption::select(
      DB::raw('
        DATE(created_at) as date, //GroupBy DATE
        avg(voltage) voltage, //Average column VOLTAGE
        avg(power) power, //Average column POWER
        ? (energy) energy //how to get all data energy in array ?
     ')
  )
  ->groupBy('date')
  ->get();

如何获取数组中的所有数据能量?

我的预期:

[
  {
    "date": "2023-05-03",
    "voltage": "215",
    "power": "0.035",
    "energy": [4,5]
  },
  {
    "date": "2023-05-06",
    "voltage": "217",
    "power": "0.045",
    "energy": [2,4]
  }
]
5ssjco0h

5ssjco0h1#

在MySQL中,可以使用GROUP_CONCAT

SELECT 
    DATE(`created_at`),
    AVG(voltage),
    AVG(power),
    GROUP_CONCAT(energy)
FROM consumption
GROUP BY DATE(`created_at`)

相关问题