[英]How can I do this SQL in Query builder laravel?
How can I do this SQL in Query builder laravel?如何在查询生成器 laravel 中执行此 SQL?
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.谁能帮助我,因为我是 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
而不是select
因为您的 select 语句具有函数和转换(date_trunc、extract、::int、count、max)。 selectRaw
supports raw sql expressions. selectRaw
支持原始 sql 表达式。whereRaw
because of the date()
function.whereRaw
相同,因为date()
function。groupByRaw
must be used because you're not grouping by a selected column.groupByRaw
,因为您没有按选定的列进行分组。orderByRaw
must be used because you're not ordering by a selected column.orderByRaw
,因为您不是按选定的列排序。 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.DB::query()->selectRaw(...->from('energydata_1001')
,你可以写DB::table('energydata_1001')->selectRaw(...
。我选择这样写更容易比较的方法。生成的 SQL 不会改变。whereRaw("date(created_at) <=?", ['2020-11-30 23:59:59'])
you could use whereDate('created_at', '<=', '2020-11-30 23:59:59')
.whereRaw("date(created_at) <=?", ['2020-11-30 23:59:59'])
你可以使用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. whereDate
在使用 PostgreSQL 时将列转换为日期,而不是使用date()
function。
whereRaw("date(created_at) >=?", ['2020-11-30 23:59:59'])
where/and 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.where/and created_at::date >= '2020-11-30 23:59:59'
。 You can do this with query builder, like:您可以使用查询生成器执行此操作,例如:
$users = DB::select('select * from users where active = ?', [1]);
With eloquent:使用 eloquent:
$user = User::select(DB::raw('select * from users where active = ?', [1]))->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.