How can I do this SQL in Query builder laravel?
SELECT date_trunc('day', created_at) AS hour_stump,
(extract(hour FROM created_at)::int / 60) AS min_slot,
count(*),
max(e4) as kwh
FROM energydata_1001
WHERE api_key_value= 'YaB8JCcE'
AND date(created_at) >= '2020-11-30 23:59:59'
AND date(created_at) <= '2020-12-29 00:00:00'
GROUP BY 1, 2
ORDER BY 1, 2;
Can anyone help me, because i'm new in laravel. Thank you.
Here's a line by line equivalent.
SQL | Builder |
---|---|
|
|
selectRaw
must be used instead of select
because your select statement has functions and casting in it (date_trunc, extract, ::int, count, max). selectRaw
supports raw sql expressions. whereRaw
because of the date()
function.groupByRaw
must be used because you're not grouping by a selected column.orderByRaw
must be used because you're not ordering by a selected column.This could be written a bit differently.
DB::query()->selectRaw(...->from('energydata_1001')
, you could write DB::table('energydata_1001')->selectRaw(...
. I chose to write it that way to make an easier comparison. The generated SQL won't change.whereRaw("date(created_at) <=?", ['2020-11-30 23:59:59'])
you could use whereDate('created_at', '<=', '2020-11-30 23:59:59')
. The difference lies in the generated SQL. whereDate
casts the column to a date instead of using the date()
function when using PostgreSQL.
whereRaw("date(created_at) >=?", ['2020-11-30 23:59:59'])
where/and date(created_at) >= '2020-11-30 23:59:59'
.whereDate('created_at', '>=', '2020-11-30 23:59:59')
where/and created_at::date >= '2020-11-30 23:59:59'
in PostgreSQL.You can do this with query builder, like:
$users = DB::select('select * from users where active = ?', [1]);
With eloquent:
$user = User::select(DB::raw('select * from users where active = ?', [1]))->get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.