我当前的选择语句:
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
最佳答案
您可以尝试按以下查询级别进行分组,这样会很快,请尝试:)
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
的用户数。然后你可以用这些日期来显示你想要的,
前任:
$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>";
以下是
mysql
中提供的date formats