Skip to content

Commit

Permalink
话题排序
Browse files Browse the repository at this point in the history
  • Loading branch information
summerblue committed Sep 20, 2019
1 parent f19e79c commit 8d25b82
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 8 deletions.
7 changes: 5 additions & 2 deletions app/Http/Controllers/CategoriesController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'));
}
Expand Down
8 changes: 4 additions & 4 deletions app/Http/Controllers/TopicsController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
29 changes: 29 additions & 0 deletions app/Models/Topic.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
}
12 changes: 10 additions & 2 deletions resources/views/topics/index.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,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 8d25b82

Please sign in to comment.