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 關注
- 156 瀏覽
添加回答
舉報