简体   繁体   中英

How can i convert an SQL query to laravel elequent

I have the following sql query working fine in a php app, but i can't figure it out in laravel elequent

The sql is basically about retrieving the number of views per day over the course of 30 days

SELECT
DATE('created_at') AS 'day',
COUNT(*) AS 'titles'
FROM `views`
where view_type ='App\\Title'
GROUP BY DATE('created_at')
order by DATE('created_at') desc
limit 30

Any help

Edit 1: DB structure

`id` bigint(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NOT NULL,
  `view_type` varchar(255) NOT NULL,
  `view_id` bigint(20) UNSIGNED NOT NULL,
DB::table("views")
->select("date ('created_at') as `day`", "count (*) as `titles`")
->where("view_type", "=", 'App\\Title')
->limit(30)
->orderBy("created_at","desc")
->groupBy("created_at")
->get();

you can use from DB::raw in laravel.

$results = DB::select(
DB::raw("SELECT
DATE('created_at') AS 'day',
COUNT(*) AS 'titles'
FROM 'views'
where view_type ='App\\Title'
GROUP BY DATE('created_at')
order by DATE('created_at') desc
limit 30");

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM