SiteAlbumLog.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Support\Carbon;
  5. class SiteAlbumLog extends Model
  6. {
  7. // 自定义日期序列化格式
  8. protected function serializeDate(\DateTimeInterface $date)
  9. {
  10. return $date->format('Y-m-d H:i:s');
  11. }
  12. protected $table = 'site_album_log';
  13. /**
  14. * 获取格式化后的日志数据
  15. *
  16. * @return array
  17. */
  18. public static function getFormattedLogs()
  19. {
  20. // 查询数据并按 created_at 降序排序
  21. $logs = self::orderBy('created_at', 'desc')->get();
  22. // 初始化结果数组
  23. $formattedLogs = [];
  24. // 遍历数据并格式化
  25. foreach ($logs as $log) {
  26. // 获取 created_at 的年份和月份(例如:2024-12)
  27. $monthKey = Carbon::parse($log->created_at)->format('Y年m月');
  28. // 将数据按月份分组
  29. if (!isset($formattedLogs[$monthKey])) {
  30. $formattedLogs[$monthKey] = [];
  31. }
  32. // 将日志数据添加到对应月份
  33. $formattedLogs[$monthKey][] = [
  34. 'id' => $log->id,
  35. 'user_name' => $log->user_name,
  36. 'action' => $log->action,
  37. 'model' => $log->model,
  38. 'content' => $log->content,
  39. 'created_at' => $log->created_at,
  40. 'updated_at' => $log->updated_at,
  41. 'content_id' => $log->content_id,
  42. ];
  43. }
  44. return $formattedLogs;
  45. }
  46. // 获取下一条日志
  47. public static function getNextLogEntry($id) {
  48. // 获取最新的 10 条数据,按 id 降序排列
  49. $logs = SiteAlbumLog::orderBy('id', 'desc')->take(10)->get();
  50. if ($logs->count() == 0) {
  51. return null;
  52. }
  53. // 查找 $id 在 $logs 中的位置
  54. $index = $logs->search(function ($log) use ($id) {
  55. return $log->id == $id;
  56. });
  57. // 如果找到 $id,并且不是最后一条数据,则返回下一条数据
  58. if ($index !== false && $index < $logs->count() - 1) {
  59. return $logs[$index + 1];
  60. }
  61. // 如果没有找到 $id 或者 $id 是最后一条数据,则返回第一条数据
  62. return $logs->first();
  63. }
  64. }