2 回答
TA贡献1786条经验 获得超13个赞
希望这样的事情能够帮助你。
在你的Post模型内部:
public function getLastThreeMonthViewsByIP($ip)
{
$data = [];
// loop 3 months
for ($i = -3; $i < 0; $i++)
{
$timestamp = strtotime("$i month");
$monthNumber = date('n', $timestamp);
// from this post
$result = $this->views()
// in this month
->whereMonth('created_at', $monthNumber)
// from this ip
->where('ip', $ip)
// group IP
->groupBy('ip')
// count all
->selectRaw('count(*) AS total')
// and return first
->first();
// if there are any results, add to data
if ($result)
{
$monthName = date('F', $timestamp);
$data[] = [
'monthNumber' => $monthNumber,
'monthName' => $monthName,
'total' => $result->total,
];
}
}
return $data;
}
TA贡献1853条经验 获得超18个赞
您可以运行下一个 SQL 查询来生成此信息:
SELECT month, count(*) AS total
FROM (
SELECT DATE_FORMAT(created_at, '%Y-%m') AS month
FROM post_views
GROUP BY month, ip
) AS calculated
GROUP BY month;
结果:
2020-01, 3
2020-02, 3
2020-03, 2
要使其与 Laravel 一起使用:
$result = DB::raw("
SELECT month, count(*) AS total
FROM (
SELECT DATE_FORMAT(created_at, '%Y-%m') AS month
FROM `post_views`
WHERE `created_at` >= DATE_FORMAT(now() - interval ? month, '%Y-%m-01')
GROUP BY DATE_FORMAT(`created_at`, '%Y-%m'), ip
) AS calculated
GROUP BY `month`
", [3]); // last 3 months
dd($result); // to see results
希望有帮助!
- 2 回答
- 0 关注
- 107 浏览
添加回答
举报