我当前的选择声明:
return User::select('id', 'created_at')
->orderBy('created_at', 'desc')
->get()
->groupBy(function($date) {
return Carbon::parse($date->created_at)->format('Y m d');
});
目前返回
2015 07 28: [
{
id: 935,
created_at: "2015-07-28 23:00:20"
}
],
2015 07 27: [
{
id: 926,
created_at: "2015-07-27 17:13:58"
},
{
id: 925,
created_at: "2015-07-27 15:00:36"
},
{
id: 924,
created_at: "2015-07-27 13:37:00"
}
]
我只想要:
Date | Users
-----+------
7/28 | 1
7/27 | 3
答案 0 :(得分:1)
您可以尝试按查询级别分组,如下所示,它会很快,试一试:)
return User::select(\DB::raw('id, count(id) numberOfUsers, DATE(created_at) dateOnly, DATE_FORMAT(created_at, "%m/%d" ) displayDate'))
->orderBy('created_at', 'desc')
->groupBy('dateOnly')
->get();
DATE(created_at) dateOnly
会选择日期时间中的日期dateOnly
,
DATE_FORMAT(created_at, "%m/%d" ) displayDate
这会将日期格式化为month/date
=> 04/07
为displayDate
,
count(id) numberOfUsers
在numberOfUsers
分组后选择每个组中dateOnly
的用户数。
然后您可以根据需要使用这些日期,
EX:
$ users =>结果来自上述查询
echo "<table border='1' style='border-collapse: collapse;'>";
echo "<tr>";
echo "<td>Date</td>";
echo "<td>Users</td>";
echo "</tr>";
foreach($users as $user) {
echo "<tr>";
echo "<td>". $user->displayDate ."</td>"; // prints the formatted date.
echo "<td>". $user->numberOfUsers ."</td>"; // prints the users count.
echo "</tr>";
}
echo "</table>";
这是[{1}}
中提供的date formats