Skip to content

Commit

Permalink
话题排序
Browse files Browse the repository at this point in the history
  • Loading branch information
summerblue committed Mar 6, 2022
1 parent 451961c commit 94af965
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 6 deletions.
8 changes: 6 additions & 2 deletions app/Http/Controllers/CategoriesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,14 @@

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)
->with('user', 'category') // 预加载防止 N+1 问题
->paginate(20);

// 传参变量话题和分类到模板中
return view('topics.index', compact('topics', 'category'));
}
Expand Down
6 changes: 4 additions & 2 deletions app/Http/Controllers/TopicsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ public function __construct()
$this->middleware('auth', ['except' => ['index', 'show']]);
}

public function index()
public function index(Request $request, Topic $topic)
{
$topics = Topic::with('user', 'category')->paginate(30);
$topics = $topic->withOrder($request->order)
->with('user', 'category') // 预加载防止 N+1 问题
->paginate(20);
return view('topics.index', compact('topics'));
}

Expand Down
27 changes: 27 additions & 0 deletions app/Models/Topic.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,31 @@ public function user()
{
return $this->belongsTo(User::class);
}

public function scopeWithOrder($query, $order)
{
// 不同的排序,使用不同的数据读取逻辑
switch ($order) {
case 'recent':
$query->recent();
break;

default:
$query->recentReplied();
break;
}
}

public function scopeRecentReplied($query)
{
// 当话题有新回复时,我们将编写逻辑来更新话题模型的 reply_count 属性,
// 此时会自动触发框架对数据模型 updated_at 时间戳的更新
return $query->orderBy('updated_at', 'desc');
}

public function scopeRecent($query)
{
// 按照创建时间排序
return $query->orderBy('created_at', 'desc');
}
}
12 changes: 10 additions & 2 deletions resources/views/topics/index.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,16 @@

<div class="card-header bg-transparent">
<ul class="nav nav-pills">
<li class="nav-item"><a class="nav-link active" href="#">最后回复</a></li>
<li class="nav-item"><a class="nav-link" href="#">最新发布</a></li>
<li class="nav-item">
<a class="nav-link {{ active_class( ! if_query('order', 'recent')) }}" href="{{ Request::url() }}?order=default">
最后回复
</a>
</li>
<li class="nav-item">
<a class="nav-link {{ active_class(if_query('order', 'recent')) }}" href="{{ Request::url() }}?order=recent">
最新发布
</a>
</li>
</ul>
</div>

Expand Down

0 comments on commit 94af965

Please sign in to comment.