laravel 5 - Eloquent relation query with some column -
i'm running query give me result.query given below
model file
public function units() { return $this->hasmany('app\powerconsumption','device_id','device_id'); }
controller file
return device::with('units')->where('user_id',2)->get();
result of query is:
[{ 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" } ]
but want run query
device::with('units')->groupby('hour') ->selectraw('round(sum(unit),4) yaxis,hour xaxis') ->where('user_id',2)->get(); }
and query generate error like
queryexception in connection.php line 713: sqlstate[42s22]: column not found: 1054 unknown column 'unit' in 'field list' (sql: select round(sum(unit),4) yaxis,hour xaxis `devices` `user_id` = 2 group `hour`)
so please me in query.
try 1
$devices = device::with(['units' => function($query){ $query->selectraw('device_id,round(sum(unit),4) yaxis,hour xaxis'); }]) ->where('user_id',2) ->get() ->each(function ($item, $key) { return $item->units->groupby('xaxis'); });
Comments
Post a Comment