Reputation: 722
I have a sql query as follow:
SELECT count(as_user_id) as Users,
CONCAT( HOUR(created_at), ' to ', CONCAT( HOUR(created_at), ':59:59' ) ) as Time_Frame
FROM content_impression
WHERE created_at >= NOW() - INTERVAL 1 DAY
GROUP BY
DATE(created_at),
HOUR(created_at)
ORDER BY count(as_user_id) DESC
The result of the query is:
Users | Time_Frame
I want to convert to eloquent query.
I have tried as like,
$results = DB::table("content_impression")
->select(DB::raw(" count(as_user_id) as Users,CONCAT( HOUR(created_at), ' to ', CONCAT( HOUR(created_at), ':59:59' ) ) as Time_Frame"))
->whereRaw("created_at >= NOW() - INTERVAL 1 DAY")
->groupByRaw("DATE(created_at),HOUR(created_at)")->orderByRaw("count(as_user_id) DESC")->get();
the error is occurred like below;
Upvotes: 0
Views: 211
Reputation: 1433
Try it like this:
where('created_at','>=',now()->subDay(1))
instead of whereRaw("created_at >= NOW() - INTERVAL 1 DAY")
.groupBy('Time_Frame')
since the error is telling you to groupBy
the columns you selected which is named as Time_frame
not DATE(created_at),HOUR(created_at)
.latest('Users')
instead of orderByRaw("count(as_user_id) DESC")
and use the alias you defind (Users
) inside the orderBy
not count(as_user_id)
.$results = DB::table("content_impression")
->selectRaw(" count(as_user_id) as Users,CONCAT( Hour(created_at), ' to ', CONCAT( Hour(created_at), ':59:59' ) ) as Time_Frame")
->where('created_at','>=',now()->subDay(1))
->groupBy('Time_Frame')->latest('Users')->get();
Upvotes: 1