我正在运行查询,它给出了结果。查询在下面给出
模型文件
public function units()
{
return $this->hasMany('App\PowerConsumption','device_id','device_id');
}
控制器文件
return Device::with('units')->where('user_id',2)->get();
此查询的结果是:
[{
device_id: 1,
user_id: 2,
device_name: "Bulb 1",
relay_num: 22,
sensor_num: 4,
status: 1,
created_at: "2016-07-11 02:11:32",
updated_at: "2016-07-19 08:25:30",
units: [
{
p_id: 1,
device_id: 1,
unit: 0.022121944444444,
month: "7",
hour: "1",
minute: "0",
created_at: "2016-07-18 00:00:00",
updated_at: "2016-07-18 00:00:00"
},
{
p_id: 2,
device_id: 1,
unit: 0.022121944444444,
month: "7",
hour: "1",
minute: "5",
created_at: "2016-07-18 00:00:00",
updated_at: "2016-07-18 00:00:00"
}
]
但我想运行此查询
Device::with('units')->groupBY('hour')
->selectRaw('round(sum(unit),4) as yAxis,hour as xAxis')
->where('user_id',2)->get();
}
此查询会产生类似
的错误QueryException in Connection.php line 713:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'unit' in 'field list' (SQL: select round(sum(unit),4) as yAxis,hour as xAxis from `devices` where `user_id` = 2 group by `hour`)
所以请帮我查询。
答案 0 :(得分:0)
试试这个
$devices = Device::with(['units' => function($query){
$query->selectRaw('device_id,round(sum(unit),4) as yAxis,hour as xAxis');
}])
->where('user_id',2)
->get()
->each(function ($item, $key) {
return $item->units->groupBy('xAxis');
});
答案 1 :(得分:0)
$devices = Device::with(['units' => function($query){
$query->selectRaw('device_id,round(sum(unit),4) as yAxis,hour as xAxis')->groupBy('xAxis);
}])
->where('user_id',2)
->get();