Laravel日期分组的日期和计数

时间:2018-12-01 02:23:51

标签: sql laravel

我有这样的表“ country_visit”

City     | Created_at
-------------------------------
Jakarta  | 2018-11-15 06:27:22
Jakarta  | 2018-11-12 05:25:24
Jakarta  | 2018-11-11 05:27:23
Jakarta  | 2018-11-15 07:27:22
Denpasar | 2018-11-15 05:27:22
Denpasar | 2018-11-12 05:27:22
Makassar | 2018-11-15 05:27:22
Makassar | 2018-11-11 05:27:22
Makassar | 2018-11-12 05:27:22

我需要这样的结果

City     | dateis    | total
-------------------------------
Jakarta  | 15 Nov    | 2
Jakarta  | 12 Nov    | 1
Jakarta  | 11 Nov    | 1

使用这样的SQL时我很成功

SELECT city,DATE_FORMAT(created_at,"%d %b") AS dateis, COUNT(city) AS total
FROM country_visit
WHERE city = 'Jakarta'
GROUP BY DATE_FORMAT(created_at, '%Y-%m-%d')

该查询与Laravel查询如何等效? 顺便说一句,我仍然使用Laravel 5.4

2 个答案:

答案 0 :(得分:0)

$table = DB::table('country_visit')
        ->select('city', DB::raw('count(*) as total'))
        ->groupBy('dateis')
        ->get();

答案 1 :(得分:0)

我解决了自己

select("city",
DB::raw("DATE_FORMAT(created_at,'%d %b') AS dateis"),
DB::raw("COUNT(city) AS total"))
->where("city","Jakarta")
->groupby(DB::raw("DATE_FORMAT(created_at, '%Y-%m-%d')"))
->get(); 

密钥在

config/database.php

某些设置需要更改 来自

'strict' => true,

'strict' => false,