PostController.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use App\Models\Post;
  5. use Illuminate\Support\Facades\Redis;
  6. class PostController extends Controller
  7. {
  8. public function show(Post $post)
  9. {
  10. $post->increment('views');
  11. if ($post->save()) {
  12. // 将当前文章浏览数 +1,存储到对应 Sorted Set 的 score 字段
  13. Redis::zincrby('popular_posts', 1, $post->id);
  14. }
  15. return 'Show Post #' . $post->id;
  16. }
  17. // 获取热门文章排行榜
  18. public function popular()
  19. {
  20. // 获取浏览器最多的前十篇文章
  21. $postIds = Redis::zrevrange('popular_posts', 0, 9);
  22. if ($postIds) {
  23. $idsStr = implode(',', $postIds);
  24. // 查询结果排序必须和传入时的 ID 排序一致
  25. $posts = Post::whereIn('id', $postIds)
  26. ->select(['id', 'title', 'views'])
  27. ->orderByRaw('field(`id`, ' . $idsStr . ')')
  28. ->get();
  29. } else {
  30. $posts = null;
  31. }
  32. dd($posts->toArray());
  33. }
  34. }