diff --git a/app/Http/Controllers/CategoriesController.php b/app/Http/Controllers/CategoriesController.php index 7fab3b465..ee493478a 100644 --- a/app/Http/Controllers/CategoriesController.php +++ b/app/Http/Controllers/CategoriesController.php @@ -8,10 +8,13 @@ class CategoriesController extends Controller { - public function show(Category $category) + public function show(Category $category, Request $request, Topic $topic) { // 读取分类 ID 关联的话题,并按每 20 条分页 - $topics = Topic::where('category_id', $category->id)->paginate(20); + $topics = $topic->withOrder($request->order) + ->where('category_id', $category->id) + ->paginate(20); + // 传参变量话题和分类到模板中 return view('topics.index', compact('topics', 'category')); } diff --git a/app/Http/Controllers/TopicsController.php b/app/Http/Controllers/TopicsController.php index 1263aeeec..88be36218 100644 --- a/app/Http/Controllers/TopicsController.php +++ b/app/Http/Controllers/TopicsController.php @@ -14,11 +14,11 @@ public function __construct() $this->middleware('auth', ['except' => ['index', 'show']]); } - public function index() - { - $topics = Topic::with('user', 'category')->paginate(30); + public function index(Request $request, Topic $topic) + { + $topics = $topic->withOrder($request->order)->paginate(20); return view('topics.index', compact('topics')); - } + } public function show(Topic $topic) { diff --git a/app/Models/Topic.php b/app/Models/Topic.php index 179fd97e8..f43c7a00b 100644 --- a/app/Models/Topic.php +++ b/app/Models/Topic.php @@ -18,4 +18,33 @@ public function user() { return $this->belongsTo(User::class); } + + public function scopeWithOrder($query, $order) + { + // 不同的排序,使用不同的数据读取逻辑 + switch ($order) { + case 'recent': + $query->recent(); + break; + + default: + $query->recentReplied(); + break; + } + // 预加载防止 N+1 问题 + return $query->with('user', 'category'); + } + + public function scopeRecentReplied($query) + { + // 当话题有新回复时,我们将编写逻辑来更新话题模型的 reply_count 属性, + // 此时会自动触发框架对数据模型 updated_at 时间戳的更新 + return $query->orderBy('updated_at', 'desc'); + } + + public function scopeRecent($query) + { + // 按照创建时间排序 + return $query->orderBy('created_at', 'desc'); + } } diff --git a/resources/views/topics/index.blade.php b/resources/views/topics/index.blade.php index 3f9e732d0..b31f74629 100644 --- a/resources/views/topics/index.blade.php +++ b/resources/views/topics/index.blade.php @@ -16,8 +16,16 @@