2 回答

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超13個(gè)贊
希望這樣的事情能夠幫助你。
在你的Post模型內(nèi)部:
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貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
您可以運(yùn)行下一個(gè) 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;
結(jié)果:
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 關(guān)注
- 172 瀏覽
添加回答
舉報(bào)