Php 按组计数(以laravel为单位)
我当前的select语句:Php 按组计数(以laravel为单位),php,mysql,sql,laravel,Php,Mysql,Sql,Laravel,我当前的select语句: return User::select('id', 'created_at') ->orderBy('created_at', 'desc') ->get() ->groupBy(function($date) { return Carbon::parse($date->crea
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
您可以尝试按以下查询级别分组,这样会很快,请尝试一下:)
DATE(created_at)dateOnly
将从datetime字段中选择日期作为dateOnly
DATE\u格式(创建于“%m/%d”)displayDate
这将格式化日期,使其显示为month/DATE
=>04/07
为displayDate
count(id)numberOfUsers
按dateOnly
分组后,在每组中选择用户数作为numberOfUsers
然后你可以用这些日期来显示你想要的
例:
$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>";
echo”“;
回声“;
呼应“日期”;
回应“用户”;
回声“;
foreach($users作为$user){
回声“;
echo“$user->displayDate.”;//打印格式化的日期。
echo“$user->numberOfUsers.”;//打印用户数。
回声“;
}
回声“;
这里是mysql中可用的
users
使用count(id)
而不是选择中的id。这将统计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>";